From 7e416c95094379db368d24e503eeb8b996391e58 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Fri, 23 Oct 2026 08:53:30 +0200 Subject: [PATCH 1/8] Integration executor: apply rule engine queue updates and evict tenant routing info Integration executors loaded the rule engine queues only at startup and never evicted the cached tenant routing info. After a tenant switched to or from an isolated rule engine they kept pushing its uplinks to the old queue until restart. - send queue update/delete notifications to integration executors (new repeated fields 2 and 3 in ToIntegrationExecutorNotificationMsg) - apply them in DefaultClusterIntegrationService - evict tenant routing info on TENANT / TENANT_PROFILE events, after the tenant profile caches (new PartitionService.evictTenantProfileInfo) --- .../queue/DefaultTbClusterService.java | 17 ++- .../discovery/HashPartitionServiceTest.java | 24 +++ .../queue/DefaultTbClusterServiceTest.java | 45 ++++++ .../DefaultClusterIntegrationService.java | 30 +++- .../DefaultClusterIntegrationServiceTest.java | 137 ++++++++++++++++++ common/proto/src/main/proto/integration.proto | 2 + .../queue/discovery/HashPartitionService.java | 5 + .../queue/discovery/PartitionService.java | 3 + 8 files changed, 257 insertions(+), 6 deletions(-) create mode 100644 common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java index 8fddd463ff..9daadc818f 100644 --- a/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java +++ b/application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java @@ -1189,7 +1189,8 @@ public class DefaultTbClusterService implements TbClusterService { ToRuleEngineNotificationMsg ruleEngineMsg = ToRuleEngineNotificationMsg.newBuilder().addAllQueueUpdateMsgs(queueUpdateMsgs).build(); ToCoreNotificationMsg coreMsg = ToCoreNotificationMsg.newBuilder().addAllQueueUpdateMsgs(queueUpdateMsgs).build(); ToTransportMsg transportMsg = ToTransportMsg.newBuilder().addAllQueueUpdateMsgs(queueUpdateMsgs).build(); - doSendQueueNotifications(ruleEngineMsg, coreMsg, transportMsg); + ToIntegrationExecutorNotificationMsg integrationExecutorMsg = ToIntegrationExecutorNotificationMsg.newBuilder().addAllQueueUpdateMsgs(queueUpdateMsgs).build(); + doSendQueueNotifications(ruleEngineMsg, coreMsg, transportMsg, integrationExecutorMsg); } @Override @@ -1207,15 +1208,20 @@ public class DefaultTbClusterService implements TbClusterService { ToRuleEngineNotificationMsg ruleEngineMsg = ToRuleEngineNotificationMsg.newBuilder().addAllQueueDeleteMsgs(queueDeleteMsgs).build(); ToCoreNotificationMsg coreMsg = ToCoreNotificationMsg.newBuilder().addAllQueueDeleteMsgs(queueDeleteMsgs).build(); ToTransportMsg transportMsg = ToTransportMsg.newBuilder().addAllQueueDeleteMsgs(queueDeleteMsgs).build(); - doSendQueueNotifications(ruleEngineMsg, coreMsg, transportMsg); + ToIntegrationExecutorNotificationMsg integrationExecutorMsg = ToIntegrationExecutorNotificationMsg.newBuilder().addAllQueueDeleteMsgs(queueDeleteMsgs).build(); + doSendQueueNotifications(ruleEngineMsg, coreMsg, transportMsg, integrationExecutorMsg); } - private void doSendQueueNotifications(ToRuleEngineNotificationMsg ruleEngineMsg, ToCoreNotificationMsg coreMsg, ToTransportMsg transportMsg) { + private void doSendQueueNotifications(ToRuleEngineNotificationMsg ruleEngineMsg, ToCoreNotificationMsg coreMsg, ToTransportMsg transportMsg, + ToIntegrationExecutorNotificationMsg integrationExecutorMsg) { Set tbRuleEngineServices = partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE); Set tbCoreServices = partitionService.getAllServiceIds(ServiceType.TB_CORE); Set tbTransportServices = partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT); + Set tbIntegrationExecutorServices = partitionService.getAllServiceIds(ServiceType.TB_INTEGRATION_EXECUTOR); // No need to push notifications twice tbTransportServices.removeAll(tbCoreServices); + tbIntegrationExecutorServices.removeAll(tbCoreServices); + tbIntegrationExecutorServices.removeAll(tbRuleEngineServices); tbCoreServices.removeAll(tbRuleEngineServices); for (String ruleEngineServiceId : tbRuleEngineServices) { @@ -1233,6 +1239,11 @@ public class DefaultTbClusterService implements TbClusterService { producerProvider.getTransportNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), transportMsg), null); toTransportNfs.incrementAndGet(); } + for (String integrationExecutorServiceId : tbIntegrationExecutorServices) { + TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_INTEGRATION_EXECUTOR, integrationExecutorServiceId); + producerProvider.getTbIntegrationExecutorNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), integrationExecutorMsg), null); + toIntegrationExecutorNfs.incrementAndGet(); + } } } 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 2e53d39e8f..44d7291515 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 @@ -459,6 +459,30 @@ public class HashPartitionServiceTest { Set.of(tenantId).equals(event.getAffectedTenants())); } + @Test + public void testEvictTenantProfileInfo_reResolvesIsolationOnlyForTenantsOfThatProfile() { + TenantProfileId isolatedProfileId = new TenantProfileId(UUID.randomUUID()); + TenantProfileId otherProfileId = new TenantProfileId(UUID.randomUUID()); + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + TenantId otherTenantId = TenantId.fromUUID(UUID.randomUUID()); + mockQueues(List.of(createQueue(TenantId.SYS_TENANT_ID, 10), createQueue(tenantId, 3), createQueue(otherTenantId, 3))); + mockRoutingInfo(tenantId, isolatedProfileId, false); + mockRoutingInfo(otherTenantId, otherProfileId, false); + HashPartitionService partitionService = createPartitionService(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + + // routing info is cached as "not isolated" + assertThat(partitionService.resolve(ServiceType.TB_RULE_ENGINE, tenantId, deviceId).getFullTopicName()).doesNotContain(".isolated."); + assertThat(partitionService.resolve(ServiceType.TB_RULE_ENGINE, otherTenantId, deviceId).getFullTopicName()).doesNotContain(".isolated."); + + mockRoutingInfo(tenantId, isolatedProfileId, true); + mockRoutingInfo(otherTenantId, otherProfileId, true); + partitionService.evictTenantProfileInfo(isolatedProfileId); + + assertThat(partitionService.resolve(ServiceType.TB_RULE_ENGINE, tenantId, deviceId).getFullTopicName()).contains(".isolated." + tenantId.getId()); + assertThat(partitionService.resolve(ServiceType.TB_RULE_ENGINE, otherTenantId, deviceId).getFullTopicName()).doesNotContain(".isolated."); + } + @Test public void testPartitionsDistribution_sameTenantDifferentQueues() { List ruleEngines = new ArrayList<>(); diff --git a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java b/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java index 013a12c26b..bba6e43124 100644 --- a/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java @@ -51,6 +51,7 @@ import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.ota.OtaPackageStateService; +import org.thingsboard.server.gen.integration.ToIntegrationExecutorNotificationMsg; import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.queue.TbQueueCallback; import org.thingsboard.server.queue.TbQueueProducer; @@ -299,6 +300,50 @@ public class DefaultTbClusterServiceTest { .send(eq(topicService.getNotificationsTopic(ServiceType.TB_TRANSPORT, monolith2)), any(TbProtoQueueMsg.class), isNull()); } + @Test + public void testOnQueuesUpdateIsSentToIntegrationExecutors() { + TbQueueProducer> tbIeQueueProducer = mockQueueNotificationTargetsWithIntegrationExecutors(); + + clusterService.onQueuesUpdate(List.of(createTestQueue())); + + ArgumentCaptor> msgCaptor = ArgumentCaptor.forClass(TbProtoQueueMsg.class); + verify(tbIeQueueProducer).send(eq(topicService.getNotificationsTopic(ServiceType.TB_INTEGRATION_EXECUTOR, "ie1")), msgCaptor.capture(), isNull()); + verifyNoMoreInteractions(tbIeQueueProducer); + ToIntegrationExecutorNotificationMsg ieMsg = msgCaptor.getValue().getValue(); + assertThat(ieMsg.getQueueUpdateMsgsCount()).isEqualTo(1); + assertThat(ieMsg.getQueueUpdateMsgs(0).getQueueName()).isEqualTo(DataConstants.MAIN_QUEUE_NAME); + assertThat(ieMsg.hasComponentLifecycle()).isFalse(); + } + + @Test + public void testOnQueuesDeleteIsSentToIntegrationExecutors() { + TbQueueProducer> tbIeQueueProducer = mockQueueNotificationTargetsWithIntegrationExecutors(); + + clusterService.onQueuesDelete(List.of(createTestQueue())); + + ArgumentCaptor> msgCaptor = ArgumentCaptor.forClass(TbProtoQueueMsg.class); + verify(tbIeQueueProducer).send(eq(topicService.getNotificationsTopic(ServiceType.TB_INTEGRATION_EXECUTOR, "ie1")), msgCaptor.capture(), isNull()); + verifyNoMoreInteractions(tbIeQueueProducer); + ToIntegrationExecutorNotificationMsg ieMsg = msgCaptor.getValue().getValue(); + assertThat(ieMsg.getQueueDeleteMsgsCount()).isEqualTo(1); + assertThat(ieMsg.getQueueDeleteMsgs(0).getQueueName()).isEqualTo(DataConstants.MAIN_QUEUE_NAME); + assertThat(ieMsg.hasComponentLifecycle()).isFalse(); + } + + // The monolith and the core run an integration executor too, but already apply queue updates from their own notifications + private TbQueueProducer> mockQueueNotificationTargetsWithIntegrationExecutors() { + when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(MONOLITH, RULE_ENGINE)); + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(MONOLITH, CORE)); + when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(MONOLITH)); + when(partitionService.getAllServiceIds(ServiceType.TB_INTEGRATION_EXECUTOR)).thenReturn(Sets.newHashSet(MONOLITH, CORE, "ie1")); + + when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(mock(TbQueueProducer.class)); + when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(mock(TbQueueProducer.class)); + TbQueueProducer> tbIeQueueProducer = mock(TbQueueProducer.class); + when(producerProvider.getTbIntegrationExecutorNotificationsMsgProducer()).thenReturn(tbIeQueueProducer); + return tbIeQueueProducer; + } + @Test public void testPushNotificationToCoreWithRestApiCallResponseMsgProto() { TopicPartitionInfo tpi = mock(TopicPartitionInfo.class); diff --git a/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java b/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java index 4e57fc5e6f..68b1c01463 100644 --- a/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java +++ b/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java @@ -12,6 +12,9 @@ import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.stereotype.Service; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.common.util.ThingsBoardThreadFactory; +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.integration.IntegrationType; import org.thingsboard.server.common.msg.TbActorMsg; import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; @@ -23,6 +26,7 @@ import org.thingsboard.server.gen.integration.ToIntegrationExecutorDownlinkMsg; import org.thingsboard.server.gen.integration.ToIntegrationExecutorNotificationMsg; import org.thingsboard.server.queue.TbQueueConsumer; import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbApplicationEventListener; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; @@ -58,6 +62,7 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener private final TbQueueIntegrationExecutorSettings integrationNotificationSettings; private final TbCoreIntegrationExecutorQueueFactory queueFactory; private final IntegrationManagerService integrationManagerService; + private final PartitionService partitionService; @Autowired(required = false) private IntegrationExecutorCacheStartupService cacheStartupService; @@ -67,11 +72,13 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener public DefaultClusterIntegrationService(TbServiceInfoProvider serviceInfoProvider, TbQueueIntegrationExecutorSettings integrationNotificationSettings, TbCoreIntegrationExecutorQueueFactory queueFactory, - IntegrationManagerService integrationManagerService) { + IntegrationManagerService integrationManagerService, + PartitionService partitionService) { this.serviceInfoProvider = serviceInfoProvider; this.integrationNotificationSettings = integrationNotificationSettings; this.queueFactory = queueFactory; this.integrationManagerService = integrationManagerService; + this.partitionService = partitionService; } private volatile ExecutorService consumersExecutor; @@ -332,9 +339,17 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener } } - private void handleNotification(UUID id, TbProtoQueueMsg msg, TbCallback callback) { + void handleNotification(UUID id, TbProtoQueueMsg msg, TbCallback callback) { ToIntegrationExecutorNotificationMsg nf = msg.getValue(); - handleComponentLifecycleMsg(id, ProtoUtils.fromProto(nf.getComponentLifecycle())); + if (nf.hasComponentLifecycle()) { + handleComponentLifecycleMsg(id, ProtoUtils.fromProto(nf.getComponentLifecycle())); + } + if (nf.getQueueUpdateMsgsCount() > 0) { + partitionService.updateQueues(nf.getQueueUpdateMsgsList()); + } + if (nf.getQueueDeleteMsgsCount() > 0) { + partitionService.removeQueues(nf.getQueueDeleteMsgsList()); + } callback.onSuccess(); } @@ -344,10 +359,19 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener componentLifecycleMsg.getEntityId().getEntityType(), componentLifecycleMsg.getEntityId(), componentLifecycleMsg.getEvent()); integrationManagerService.handleComponentLifecycleMsg(componentLifecycleMsg); + // after the tenant profile caches are evicted, so that the routing info is re-read from the updated profile + evictTenantRoutingInfo(componentLifecycleMsg.getEntityId()); } log.trace("[{}] Forwarding message to App Actor {}", id, actorMsg); } + private void evictTenantRoutingInfo(EntityId entityId) { + switch (entityId.getEntityType()) { + case TENANT -> partitionService.evictTenantInfo(TenantId.fromUUID(entityId.getId())); + case TENANT_PROFILE -> partitionService.evictTenantProfileInfo(new TenantProfileId(entityId.getId())); + } + } + private void refreshIntegrationsByType(IntegrationType type) { try { Set partitions = getLatestPartitionsFromQueue(type); diff --git a/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java b/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java new file mode 100644 index 0000000000..25c5ac14c1 --- /dev/null +++ b/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.integration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.IntegrationId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.TenantProfileId; +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; +import org.thingsboard.server.common.msg.queue.TbCallback; +import org.thingsboard.server.common.util.ProtoUtils; +import org.thingsboard.server.gen.integration.ToIntegrationExecutorNotificationMsg; +import org.thingsboard.server.gen.transport.TransportProtos.QueueDeleteMsg; +import org.thingsboard.server.gen.transport.TransportProtos.QueueUpdateMsg; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.queue.provider.TbCoreIntegrationExecutorQueueFactory; +import org.thingsboard.server.queue.settings.TbQueueIntegrationExecutorSettings; + +import java.util.List; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +@ExtendWith(MockitoExtension.class) +class DefaultClusterIntegrationServiceTest { + + @Mock + private TbServiceInfoProvider serviceInfoProvider; + @Mock + private TbQueueIntegrationExecutorSettings integrationNotificationSettings; + @Mock + private TbCoreIntegrationExecutorQueueFactory queueFactory; + @Mock + private IntegrationManagerService integrationManagerService; + @Mock + private PartitionService partitionService; + @Mock + private TbCallback callback; + + private DefaultClusterIntegrationService service; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @BeforeEach + void setUp() { + service = new DefaultClusterIntegrationService(serviceInfoProvider, integrationNotificationSettings, queueFactory, + integrationManagerService, partitionService); + } + + @Test + void givenQueueUpdateNotification_whenHandled_thenQueuesAreUpdatedInPartitionService() { + QueueUpdateMsg queueUpdateMsg = QueueUpdateMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setQueueName("Main") + .setQueueTopic("tb_rule_engine.main") + .setPartitions(3) + .build(); + + handle(ToIntegrationExecutorNotificationMsg.newBuilder().addQueueUpdateMsgs(queueUpdateMsg).build()); + + verify(partitionService).updateQueues(List.of(queueUpdateMsg)); + verify(integrationManagerService, never()).handleComponentLifecycleMsg(any()); + verify(callback).onSuccess(); + } + + @Test + void givenQueueDeleteNotification_whenHandled_thenQueuesAreRemovedFromPartitionService() { + QueueDeleteMsg queueDeleteMsg = QueueDeleteMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setQueueName("Main") + .build(); + + handle(ToIntegrationExecutorNotificationMsg.newBuilder().addQueueDeleteMsgs(queueDeleteMsg).build()); + + verify(partitionService).removeQueues(List.of(queueDeleteMsg)); + verify(integrationManagerService, never()).handleComponentLifecycleMsg(any()); + verify(callback).onSuccess(); + } + + @Test + void givenTenantUpdated_whenHandled_thenTenantRoutingInfoIsEvictedAfterTenantProfileCaches() { + handle(lifecycleNotification(tenantId, tenantId)); + + // the routing info is re-read from the tenant profile cache, so it must be evicted after that cache + InOrder inOrder = inOrder(integrationManagerService, partitionService); + inOrder.verify(integrationManagerService).handleComponentLifecycleMsg(any()); + inOrder.verify(partitionService).evictTenantInfo(tenantId); + verify(callback).onSuccess(); + } + + @Test + void givenTenantProfileUpdated_whenHandled_thenRoutingInfoOfItsTenantsIsEvictedAfterTenantProfileCaches() { + TenantProfileId tenantProfileId = new TenantProfileId(UUID.randomUUID()); + + handle(lifecycleNotification(TenantId.SYS_TENANT_ID, tenantProfileId)); + + InOrder inOrder = inOrder(integrationManagerService, partitionService); + inOrder.verify(integrationManagerService).handleComponentLifecycleMsg(any()); + inOrder.verify(partitionService).evictTenantProfileInfo(tenantProfileId); + verify(callback).onSuccess(); + } + + @Test + void givenIntegrationUpdated_whenHandled_thenRoutingInfoIsKept() { + handle(lifecycleNotification(tenantId, new IntegrationId(UUID.randomUUID()))); + + verify(integrationManagerService).handleComponentLifecycleMsg(any()); + verifyNoInteractions(partitionService); + verify(callback).onSuccess(); + } + + private ToIntegrationExecutorNotificationMsg lifecycleNotification(TenantId tenantId, EntityId entityId) { + ComponentLifecycleMsg msg = new ComponentLifecycleMsg(tenantId, entityId, ComponentLifecycleEvent.UPDATED); + return ToIntegrationExecutorNotificationMsg.newBuilder().setComponentLifecycle(ProtoUtils.toProto(msg)).build(); + } + + private void handle(ToIntegrationExecutorNotificationMsg nf) { + UUID id = UUID.randomUUID(); + service.handleNotification(id, new TbProtoQueueMsg<>(id, nf), callback); + } + +} diff --git a/common/proto/src/main/proto/integration.proto b/common/proto/src/main/proto/integration.proto index 2f6a4b4fe6..2284b1dd70 100644 --- a/common/proto/src/main/proto/integration.proto +++ b/common/proto/src/main/proto/integration.proto @@ -343,6 +343,8 @@ message IntegrationApiResponseMsg { /* High priority messages with low latency are handled by ThingsBoard Integration Executor Service separately */ message ToIntegrationExecutorNotificationMsg { transport.ComponentLifecycleMsgProto componentLifecycle = 1; + repeated transport.QueueUpdateMsg queueUpdateMsgs = 2; + repeated transport.QueueDeleteMsg queueDeleteMsgs = 3; } message IntegrationValidationRequestProto { 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 1675d734cf..6d2371bf4a 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 @@ -616,6 +616,11 @@ public class HashPartitionService implements PartitionService { tenantRoutingInfoMap.remove(tenantId); } + @Override + public void evictTenantProfileInfo(TenantProfileId tenantProfileId) { + tenantRoutingInfoMap.values().removeIf(routingInfo -> tenantProfileId.equals(routingInfo.getProfileId())); + } + @Override public int countTransportsByType(String type) { var list = tbTransportServicesByType.get(type); diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java index 6f57c1e7e2..9d4804e9eb 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/discovery/PartitionService.java @@ -5,6 +5,7 @@ package org.thingsboard.server.queue.discovery; 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.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.gen.transport.TransportProtos; @@ -61,6 +62,8 @@ public interface PartitionService { void evictTenantInfo(TenantId tenantId); + void evictTenantProfileInfo(TenantProfileId tenantProfileId); + int countTransportsByType(String type); int getIntegrationExecutorPartitionsCount(); From f2785f3b1065becb5ae11b99f84be0ff2249afe5 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 19:10:47 +0100 Subject: [PATCH 2/8] Evict stale API key cache entry when the key value changes --- .../server/dao/pat/ApiKeyServiceImpl.java | 24 ++++++++++++-- .../server/dao/service/ApiKeyServiceTest.java | 33 +++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index 7a2fbda4bf..a1843b72a5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java @@ -27,6 +27,7 @@ import org.thingsboard.server.dao.eventsourcing.SaveEntityEvent; import org.thingsboard.server.dao.service.validator.ApiKeyDataValidator; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -82,8 +83,13 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService + * Authentication resolves a key by value straight from the cache, so both the enabled flag and the value must + * trigger an eviction. A regular update preserves the value, but a save with an explicit value (e.g. an edge + * applying a key rotated on the cloud) replaces it, leaving the old value to authenticate from the cache. + */ + private static boolean isPublishEvictRequired(ApiKey old, ApiKey apiKey) { + return old != null + && (old.isEnabled() != apiKey.isEnabled() + || !Objects.equals(old.getValue(), apiKey.getValue())); + } + @Override public EntityType getEntityType() { return EntityType.API_KEY; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java index 157012d1c9..4fb8942142 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java @@ -130,6 +130,39 @@ public class ApiKeyServiceTest extends AbstractServiceTest { Assert.assertEquals(savedApiKey.getValue(), foundApiKey.getValue()); } + @Test + public void testSaveApiKeyWithNewValue_oldValueEvictedFromCache() { + ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION); + ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo); + String originalValue = savedApiKey.getValue(); + // authentication resolves the key by value and caches the lookup + Assert.assertNotNull(apiKeyService.findApiKeyByValue(originalValue)); + + String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32); + apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false); + + Assert.assertNull("Old API key value must not resolve after the value changed", apiKeyService.findApiKeyByValue(originalValue)); + ApiKey foundByNewValue = apiKeyService.findApiKeyByValue(newValue); + Assert.assertNotNull(foundByNewValue); + Assert.assertEquals(savedApiKey.getId(), foundByNewValue.getId()); + } + + @Test + public void testSaveApiKeyWithNewValue_cachedMissForNewValueEvicted() { + ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION); + ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo); + + String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32); + // a failed authentication attempt caches the miss for the not-yet-saved value + Assert.assertNull(apiKeyService.findApiKeyByValue(newValue)); + + apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false); + + ApiKey foundByNewValue = apiKeyService.findApiKeyByValue(newValue); + Assert.assertNotNull("New API key value must resolve after it is saved", foundByNewValue); + Assert.assertEquals(savedApiKey.getId(), foundByNewValue.getId()); + } + @Test public void testFindApiKeysByUserId() { int size = 3; From 192836945ff1ca81a6953da11459002438439ba9 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 20:00:51 +0100 Subject: [PATCH 3/8] Verify exact API key cache evictions and call counts --- .../dao/pat/ApiKeyCacheEvictionTest.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java diff --git a/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java b/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java new file mode 100644 index 0000000000..ee6ab565b2 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.dao.pat; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.pat.ApiKey; +import org.thingsboard.server.common.data.pat.ApiKeyInfo; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.dao.service.AbstractServiceTest; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.dao.user.UserService; + +/** + * Verifies the exact cache interactions of {@link ApiKeyService} saves: which {@link ApiKeyCacheKey}s are evicted + * and how many times. Lives in this package because {@link ApiKeyCacheKey} is package-private. + */ +@DaoSqlTest +public class ApiKeyCacheEvictionTest extends AbstractServiceTest { + + @Autowired + ApiKeyService apiKeyService; + + @Autowired + UserService userService; + + @MockitoSpyBean + TbTransactionalCache apiKeyCache; + + private UserId userId; + + @Before + public void before() { + User tenantAdmin = new User(); + tenantAdmin.setAuthority(Authority.TENANT_ADMIN); + tenantAdmin.setTenantId(tenantId); + tenantAdmin.setEmail("tenant-api-key-cache@thingsboard.org"); + User user = userService.saveUser(TenantId.SYS_TENANT_ID, tenantAdmin); + userId = user.getId(); + } + + @After + public void after() { + apiKeyService.deleteByTenantId(tenantId); + User user = userService.findUserById(tenantId, userId); + userService.deleteUser(tenantId, user); + } + + @Test + public void testSaveApiKeyWithNewValue_evictsOldAndNewValueExactlyOnce() { + ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo()); + String originalValue = savedApiKey.getValue(); + String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32); + Mockito.clearInvocations(apiKeyCache); + + apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false); + + Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(originalValue)); + Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(newValue)); + Mockito.verify(apiKeyCache, Mockito.times(2)).evict(Mockito.any(ApiKeyCacheKey.class)); + } + + @Test + public void testDisableApiKey_evictsValueExactlyOnce() { + ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo()); + String value = savedApiKey.getValue(); + savedApiKey.setEnabled(false); + Mockito.clearInvocations(apiKeyCache); + + apiKeyService.saveApiKey(tenantId, savedApiKey); + + Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(value)); + Mockito.verify(apiKeyCache, Mockito.times(1)).evict(Mockito.any(ApiKeyCacheKey.class)); + } + + @Test + public void testUpdateApiKeyDescription_noEviction() { + ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo()); + savedApiKey.setDescription("Updated description, cached state unchanged"); + Mockito.clearInvocations(apiKeyCache); + + apiKeyService.saveApiKey(tenantId, savedApiKey); + + Mockito.verify(apiKeyCache, Mockito.never()).evict(Mockito.any(ApiKeyCacheKey.class)); + } + + private ApiKeyInfo createApiKeyInfo() { + ApiKeyInfo apiKeyInfo = new ApiKeyInfo(); + apiKeyInfo.setTenantId(tenantId); + apiKeyInfo.setUserId(userId); + apiKeyInfo.setDescription("API key cache eviction test"); + apiKeyInfo.setEnabled(true); + return apiKeyInfo; + } + +} From 91c1d9a619b8f045704542e02b378d13f131731a Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 20:00:51 +0100 Subject: [PATCH 4/8] Shorten isPublishEvictRequired javadoc --- .../org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index a1843b72a5..717466e034 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java @@ -187,12 +187,8 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService - * Authentication resolves a key by value straight from the cache, so both the enabled flag and the value must - * trigger an eviction. A regular update preserves the value, but a save with an explicit value (e.g. an edge - * applying a key rotated on the cloud) replaces it, leaving the old value to authenticate from the cache. + * Authentication resolves keys by value straight from the cache, so a changed enabled flag or value (explicit-value + * save, e.g. edge sync) requires eviction. A newly created key has nothing cached yet, hence the null check. */ private static boolean isPublishEvictRequired(ApiKey old, ApiKey apiKey) { return old != null From 6d31dfd95854fb68a16a694cdebf520ec2eb6431 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 28 Oct 2026 16:53:13 +0100 Subject: [PATCH 5/8] Evict cached miss when an API key is created with an explicit value --- .../server/dao/pat/ApiKeyServiceImpl.java | 13 ++++++------ .../dao/pat/ApiKeyCacheEvictionTest.java | 18 +++++++++++++++++ .../server/dao/service/ApiKeyServiceTest.java | 20 +++++++++++++++++++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index 717466e034..418b56c9b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java @@ -86,10 +86,10 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService Date: Sat, 31 Oct 2026 11:06:05 +0100 Subject: [PATCH 6/8] Fixed TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY being ignored by standalone transports The transport.activity.reporting_strategy property was defined only in thingsboard.yml, so standalone MQTT, HTTP, CoAP, LwM2M and SNMP transport services silently ignored TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY and always used the LAST strategy. Add the same transport.activity block to each tb-*-transport.yml. --- transport/coap/src/main/resources/tb-coap-transport.yml | 8 ++++++++ transport/http/src/main/resources/tb-http-transport.yml | 8 ++++++++ transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml | 8 ++++++++ transport/mqtt/src/main/resources/tb-mqtt-transport.yml | 8 ++++++++ transport/snmp/src/main/resources/tb-snmp-transport.yml | 8 ++++++++ 5 files changed, 40 insertions(+) diff --git a/transport/coap/src/main/resources/tb-coap-transport.yml b/transport/coap/src/main/resources/tb-coap-transport.yml index db8e0fc034..b7eb75383d 100644 --- a/transport/coap/src/main/resources/tb-coap-transport.yml +++ b/transport/coap/src/main/resources/tb-coap-transport.yml @@ -151,6 +151,14 @@ transport: inactivity_timeout: "${TB_TRANSPORT_SESSIONS_INACTIVITY_TIMEOUT:600000}" # Interval of periodic check for expired sessions and report of the changes to session last activity time report_timeout: "${TB_TRANSPORT_SESSIONS_REPORT_TIMEOUT:3000}" + activity: + # This property specifies the strategy for reporting activity events within each reporting period. + # The accepted values are 'FIRST', 'LAST', 'FIRST_AND_LAST' and 'ALL'. + #
  • 'FIRST': Only the first activity event in each reporting period is reported.
  • + #
  • 'LAST': Only the last activity event in the reporting period is reported.
  • + #
  • 'FIRST_AND_LAST': Both the first and last activity events in the reporting period are reported.
  • + #
  • 'ALL': All activity events in the reporting period are reported.
+ reporting_strategy: "${TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY:LAST}" json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:true}" diff --git a/transport/http/src/main/resources/tb-http-transport.yml b/transport/http/src/main/resources/tb-http-transport.yml index 57d33aa88d..800b10c97b 100644 --- a/transport/http/src/main/resources/tb-http-transport.yml +++ b/transport/http/src/main/resources/tb-http-transport.yml @@ -183,6 +183,14 @@ transport: inactivity_timeout: "${TB_TRANSPORT_SESSIONS_INACTIVITY_TIMEOUT:600000}" # Interval of periodic check for expired sessions and report of the changes to session last activity time report_timeout: "${TB_TRANSPORT_SESSIONS_REPORT_TIMEOUT:3000}" + activity: + # This property specifies the strategy for reporting activity events within each reporting period. + # The accepted values are 'FIRST', 'LAST', 'FIRST_AND_LAST' and 'ALL'. + #
  • 'FIRST': Only the first activity event in each reporting period is reported.
  • + #
  • 'LAST': Only the last activity event in the reporting period is reported.
  • + #
  • 'FIRST_AND_LAST': Both the first and last activity events in the reporting period are reported.
  • + #
  • 'ALL': All activity events in the reporting period are reported.
+ reporting_strategy: "${TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY:LAST}" json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:true}" diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index 1846e6856a..d71174e27a 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -143,6 +143,14 @@ transport: inactivity_timeout: "${TB_TRANSPORT_SESSIONS_INACTIVITY_TIMEOUT:600000}" # Interval of periodic check for expired sessions and report of the changes to session last activity time report_timeout: "${TB_TRANSPORT_SESSIONS_REPORT_TIMEOUT:3000}" + activity: + # This property specifies the strategy for reporting activity events within each reporting period. + # The accepted values are 'FIRST', 'LAST', 'FIRST_AND_LAST' and 'ALL'. + #
  • 'FIRST': Only the first activity event in each reporting period is reported.
  • + #
  • 'LAST': Only the last activity event in the reporting period is reported.
  • + #
  • 'FIRST_AND_LAST': Both the first and last activity events in the reporting period are reported.
  • + #
  • 'ALL': All activity events in the reporting period are reported.
+ reporting_strategy: "${TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY:LAST}" json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:false}" diff --git a/transport/mqtt/src/main/resources/tb-mqtt-transport.yml b/transport/mqtt/src/main/resources/tb-mqtt-transport.yml index 7314b9733e..d994824a4f 100644 --- a/transport/mqtt/src/main/resources/tb-mqtt-transport.yml +++ b/transport/mqtt/src/main/resources/tb-mqtt-transport.yml @@ -206,6 +206,14 @@ transport: inactivity_timeout: "${TB_TRANSPORT_SESSIONS_INACTIVITY_TIMEOUT:600000}" # Interval of periodic check for expired sessions and report of the changes to session last activity time report_timeout: "${TB_TRANSPORT_SESSIONS_REPORT_TIMEOUT:3000}" + activity: + # This property specifies the strategy for reporting activity events within each reporting period. + # The accepted values are 'FIRST', 'LAST', 'FIRST_AND_LAST' and 'ALL'. + #
  • 'FIRST': Only the first activity event in each reporting period is reported.
  • + #
  • 'LAST': Only the last activity event in the reporting period is reported.
  • + #
  • 'FIRST_AND_LAST': Both the first and last activity events in the reporting period are reported.
  • + #
  • 'ALL': All activity events in the reporting period are reported.
+ reporting_strategy: "${TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY:LAST}" json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:true}" diff --git a/transport/snmp/src/main/resources/tb-snmp-transport.yml b/transport/snmp/src/main/resources/tb-snmp-transport.yml index 527a653bb7..aa4b7fd3cb 100644 --- a/transport/snmp/src/main/resources/tb-snmp-transport.yml +++ b/transport/snmp/src/main/resources/tb-snmp-transport.yml @@ -164,6 +164,14 @@ transport: inactivity_timeout: "${TB_TRANSPORT_SESSIONS_INACTIVITY_TIMEOUT:600000}" # Interval of periodic check for expired sessions and report of the changes to session last activity time report_timeout: "${TB_TRANSPORT_SESSIONS_REPORT_TIMEOUT:3000}" + activity: + # This property specifies the strategy for reporting activity events within each reporting period. + # The accepted values are 'FIRST', 'LAST', 'FIRST_AND_LAST' and 'ALL'. + #
  • 'FIRST': Only the first activity event in each reporting period is reported.
  • + #
  • 'LAST': Only the last activity event in the reporting period is reported.
  • + #
  • 'FIRST_AND_LAST': Both the first and last activity events in the reporting period are reported.
  • + #
  • 'ALL': All activity events in the reporting period are reported.
+ reporting_strategy: "${TB_TRANSPORT_ACTIVITY_REPORTING_STRATEGY:LAST}" json: # Cast String data types to Numeric if possible when processing Telemetry/Attributes JSON type_cast_enabled: "${JSON_TYPE_CAST_ENABLED:true}" From 0d2b1f1c42dc5618ec9fb0bbc4c2c00a78e51284 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 12 Nov 2026 14:40:19 +0100 Subject: [PATCH 7/8] Fix edge telemetry and attributes processing for entity groups --- .../service/edge/EdgeEntityTenantChecker.java | 9 +++- .../server/edge/TelemetryEdgeTest.java | 45 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java index 5d3397a509..90ae697f37 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java @@ -5,6 +5,7 @@ package org.thingsboard.server.service.edge; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.HasOwnerId; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; @@ -35,7 +36,13 @@ public class EdgeEntityTenantChecker { } try { return entityService.fetchEntity(tenantId, entityId) - .map(entity -> entity instanceof HasTenantId hasTenantId && tenantId.equals(hasTenantId.getTenantId())) + .map(entity -> { + if (entity instanceof HasTenantId hasTenantId) { + return tenantId.equals(hasTenantId.getTenantId()); + } + // entities without own tenant id (entity groups) belong to the tenant of their owner + return entity instanceof HasOwnerId hasOwnerId && isTenantEntity(tenantId, hasOwnerId.getOwnerId()); + }) .orElse(false); } catch (IllegalArgumentException e) { log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); diff --git a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java index af2522897e..031b646b00 100644 --- a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java @@ -13,11 +13,13 @@ import org.junit.Test; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.edge.EdgeEventType; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.AttributeDeleteMsg; @@ -345,4 +347,47 @@ public class TelemetryEdgeTest extends AbstractEdgeTest { }); } + @Test + public void testSendEntityGroupAttributesAndTelemetryToCloud() throws Exception { + EntityGroup entityGroup = createEntityGroupAndAssignToEdge(EntityType.DEVICE, "TelemetryDeviceGroup", tenantId); + + long ts = System.currentTimeMillis(); + EntityDataProto entityData = EntityDataProto.newBuilder() + .setEntityIdMSB(entityGroup.getUuidId().getMostSignificantBits()) + .setEntityIdLSB(entityGroup.getUuidId().getLeastSignificantBits()) + .setEntityType(entityGroup.getId().getEntityType().name()) + .setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder() + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupKey") + .setType(TransportProtos.KeyValueType.STRING_V) + .setStringV("groupValue").build()) + .build()) + .setPostAttributeScope(DataConstants.SERVER_SCOPE) + .setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder() + .addTsKvList(TransportProtos.TsKvListProto.newBuilder() + .setTs(ts) + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupTemperature") + .setType(TransportProtos.KeyValueType.LONG_V) + .setLongV(25).build()) + .build()) + .build()) + .build(); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData)); + + String valuesUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + entityGroup.getUuidId() + "/values/"; + Awaitility.await() + .atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> { + JsonNode attributes = doGetAsync(valuesUrl + "attributes/" + DataConstants.SERVER_SCOPE, JsonNode.class); + Assert.assertEquals(1, attributes.size()); + Assert.assertEquals("groupKey", attributes.get(0).get("key").asText()); + Assert.assertEquals("groupValue", attributes.get(0).get("value").asText()); + JsonNode timeseries = doGetAsync(valuesUrl + "timeseries?keys=groupTemperature", JsonNode.class); + Assert.assertEquals(1, timeseries.get("groupTemperature").size()); + Assert.assertEquals(ts, timeseries.get("groupTemperature").get(0).get("ts").asLong()); + Assert.assertEquals("25", timeseries.get("groupTemperature").get(0).get("value").asText()); + }); + } + } From 9c0c4773c3c970ccbe5ae842ab58c8c73671e4e1 Mon Sep 17 00:00:00 2001 From: Shvaika Dmytro Date: Thu, 12 Nov 2026 16:04:59 +0200 Subject: [PATCH 8/8] IoT Hub installed items: no update button for an item without a published version (#16640) --- .../iot-hub/iot-hub-installed-items-table.component.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index bc550bd817..7f1dbac04e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -43,7 +43,7 @@ @if (updatesChecked) { @let pubInfo = getPublishedVersionInfo(item); - @if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) { + @if (pubInfo?.publishedVersionId && pubInfo.publishedVersionId !== item.itemVersionId) {
@if (!itemVersion) {