From 361e267db4aeddc9b791b69e48fe2798bed4f670 Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Fri, 5 Jun 2026 15:06:55 +0300 Subject: [PATCH 001/213] Edge: prevent disconnect notification spam from flapping edges --- .../service/edge/rpc/EdgeGrpcService.java | 104 ++++++++++++++++-- .../src/main/resources/thingsboard.yml | 5 + .../edge/EdgeConnectionNotificationTest.java | 96 ++++++++++++++++ 3 files changed, 194 insertions(+), 11 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 072a4878d5..7f57101205 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -41,7 +41,6 @@ import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.StringUtils; -import org.thingsboard.server.common.transport.config.ssl.PemSslCredentials; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.id.EdgeId; @@ -58,6 +57,7 @@ import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.edge.EdgeSessionMsg; import org.thingsboard.server.common.msg.edge.FromEdgeSyncResponse; import org.thingsboard.server.common.msg.edge.ToEdgeSyncRequest; +import org.thingsboard.server.common.transport.config.ssl.PemSslCredentials; import org.thingsboard.server.gen.edge.v1.EdgeRpcServiceGrpc; import org.thingsboard.server.gen.edge.v1.RequestMsg; import org.thingsboard.server.gen.edge.v1.ResponseMsg; @@ -68,7 +68,6 @@ import org.thingsboard.server.queue.provider.TbCoreQueueFactory; import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.EdgeContextComponent; -import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import java.io.IOException; import java.util.ArrayList; @@ -103,6 +102,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private final ConcurrentMap sessionNewEventsLocks = new ConcurrentHashMap<>(); private final Map sessionNewEvents = new HashMap<>(); private final ConcurrentMap> sessionEdgeEventChecks = new ConcurrentHashMap<>(); + private final ConcurrentMap> pendingDisconnectNotifications = new ConcurrentHashMap<>(); private final ConcurrentMap> localSyncEdgeRequests = new ConcurrentHashMap<>(); private final ConcurrentMap edgeEventsMigrationProcessed = new ConcurrentHashMap<>(); private final List zombieSessions = new ArrayList<>(); @@ -136,6 +136,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Value("${edges.max_high_priority_queue_size_per_session:10000}") private int maxHighPriorityQueueSizePerSession; + @Value("${edges.connectivity.disconnect_notification_delay_ms:60000}") + private long disconnectNotificationDelayMs; + @Autowired @Lazy private EdgeContextComponent ctx; @@ -239,6 +242,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i sessionEdgeEventChecks.remove(edgeId); } } + pendingDisconnectNotifications.values().forEach(task -> { + if (task != null && !task.isDone()) { + task.cancel(false); + } + }); + pendingDisconnectNotifications.clear(); if (edgeEventProcessingExecutorService != null) { edgeEventProcessingExecutorService.shutdownNow(); } @@ -321,6 +330,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } + cancelPendingDisconnectNotification(edgeId); cancelScheduleEdgeEventsCheck(edgeId); } } @@ -383,7 +393,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i long lastConnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs); edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); - pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); + // If the edge reconnected within the disconnect-notification delay window, suppress the pending + // "disconnected" notification - the drop was transient (debounce for flapping edges). + cancelPendingDisconnectNotification(edgeId); + pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); + notifyEdgeConnectivity(tenantId, edge, true); cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); @@ -545,7 +559,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); + pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); + scheduleDisconnectNotification(tenantId, edge); cancelScheduleEdgeEventsCheck(edgeId); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -617,7 +632,33 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } } - private void pushRuleEngineMessage(TenantId tenantId, Edge edge, long ts, TbMsgType msgType) { + private static class AttributeSaveCallback implements FutureCallback { + + private final TenantId tenantId; + private final EdgeId edgeId; + private final String key; + private final Object value; + + AttributeSaveCallback(TenantId tenantId, EdgeId edgeId, String key, Object value) { + this.tenantId = tenantId; + this.edgeId = edgeId; + this.key = key; + this.value = value; + } + + @Override + public void onSuccess(@Nullable Void result) { + log.trace("[{}][{}] Successfully updated attribute [{}] with value [{}]", tenantId, edgeId, key, value); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}][{}] Failed to update attribute [{}] with value [{}]", tenantId, edgeId, key, value, t); + } + + } + + private void pushStateEventToRuleEngine(TenantId tenantId, Edge edge, long ts, TbMsgType msgType) { try { EdgeId edgeId = edge.getId(); ObjectNode edgeState = JacksonUtil.newObjectNode(); @@ -629,12 +670,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i edgeState.put(ACTIVITY_STATE, false); edgeState.put(LAST_DISCONNECT_TIME, ts); } - ctx.getRuleProcessor().process(EdgeConnectionTrigger.builder() - .tenantId(tenantId) - .customerId(edge.getCustomerId()) - .edgeId(edgeId) - .edgeName(edge.getName()) - .connected(isConnected).build()); String data = JacksonUtil.toString(edgeState); TbMsgMetaData md = new TbMsgMetaData(); if (!persistToTelemetry) { @@ -655,6 +690,53 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } } + private void notifyEdgeConnectivity(TenantId tenantId, Edge edge, boolean connected) { + try { + ctx.getRuleProcessor().process(EdgeConnectionTrigger.builder() + .tenantId(tenantId) + .customerId(edge.getCustomerId()) + .edgeId(edge.getId()) + .edgeName(edge.getName()) + .connected(connected).build()); + } catch (Exception e) { + log.warn("[{}][{}] Failed to process edge connectivity notification (connected={})", tenantId, edge.getId(), connected, e); + } + } + + private void scheduleDisconnectNotification(TenantId tenantId, Edge edge) { + if (disconnectNotificationDelayMs <= 0) { + notifyEdgeConnectivity(tenantId, edge, false); + return; + } + EdgeId edgeId = edge.getId(); + pendingDisconnectNotifications.compute(edgeId, (id, existing) -> { + if (existing != null && !existing.isDone()) { + existing.cancel(false); + } + return executorService.schedule(() -> fireDelayedDisconnectNotification(tenantId, edge), + disconnectNotificationDelayMs, TimeUnit.MILLISECONDS); + }); + } + + private void fireDelayedDisconnectNotification(TenantId tenantId, Edge edge) { + EdgeId edgeId = edge.getId(); + pendingDisconnectNotifications.remove(edgeId); + // Re-verify the edge is still disconnected. The cache is cluster-wide, so this also covers the case + // where the edge dropped on this node and reconnected to a different TB-Core node within the window. + if (sessions.containsKey(edgeId) || edgeIdServiceIdCache.get(edgeId) != null) { + log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", tenantId, edgeId); + return; + } + notifyEdgeConnectivity(tenantId, edge, false); + } + + private void cancelPendingDisconnectNotification(EdgeId edgeId) { + ScheduledFuture pending = pendingDisconnectNotifications.remove(edgeId); + if (pending != null && !pending.isDone()) { + pending.cancel(false); + } + } + private void cleanupZombieSessions() { try { tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 454c59d7d7..0cb3e57ae8 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1642,6 +1642,11 @@ edges: state: # Persist state of edge (active, last connect, last disconnect) into timeseries or attributes tables. 'false' means to store edge state into attributes table persistToTelemetry: "${EDGES_PERSIST_STATE_TO_TELEMETRY:false}" + connectivity: + # Delay (ms) before sending an edge "disconnected" notification. Suppressed if the edge reconnects within + # this window - debounces flapping edges from spamming the notification center. Only the notification is + # delayed; rule-engine events and state attributes update immediately. Set to 0 to notify immediately. + disconnect_notification_delay_ms: "${TB_EDGE_DISCONNECT_NOTIFICATION_DELAY_MS:60000}" stats: # Enable or disable reporting of edge communication stats (true or false) enabled: "${EDGES_STATS_ENABLED:true}" diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java new file mode 100644 index 0000000000..f72ad51f4a --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java @@ -0,0 +1,96 @@ +/** + * 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.edge; + +import org.junit.Test; +import org.mockito.ArgumentMatcher; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; +import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.controller.AbstractWebTest; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.edge.imitator.EdgeImitator; +import org.thingsboard.server.gen.edge.v1.OAuth2ClientUpdateMsg; +import org.thingsboard.server.gen.edge.v1.OAuth2DomainUpdateMsg; + +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@DaoSqlTest +@TestPropertySource(properties = { + "edges.connectivity.disconnect_notification_delay_ms=5000" +}) +public class EdgeConnectionNotificationTest extends AbstractEdgeTest { + + private static final long DELAY_MS = 5000L; + + @MockitoSpyBean + private NotificationRuleProcessor notificationRuleProcessor; + + @Test + public void givenEdgeStaysDisconnected_whenDelayElapses_thenDisconnectNotificationSent() throws Exception { + clearInvocations(notificationRuleProcessor); + + edgeImitator.disconnect(); + + // After the configured delay, the "disconnected" notification is sent exactly once. + await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> + verify(notificationRuleProcessor, times(1)).process(argThat(edgeConnectionTrigger(false)))); + } + + @Test + public void givenEdgeReconnectsWithinDelay_whenEdgeFlaps_thenDisconnectNotificationSuppressed() throws Exception { + clearInvocations(notificationRuleProcessor); + + // Edge drops... + edgeImitator.disconnect(); + // Ensure the server processed the disconnect (and scheduled the delayed notification) before reconnecting. + TimeUnit.SECONDS.sleep(1); + + // ...and reconnects within the delay window, which must cancel the pending "disconnected" notification. + EdgeImitator reconnected = new EdgeImitator(EDGE_HOST, EDGE_PORT, edge.getRoutingKey(), edge.getSecret()); + reconnected.ignoreType(OAuth2ClientUpdateMsg.class); + reconnected.ignoreType(OAuth2DomainUpdateMsg.class); + reconnected.connect(); + edgeImitator = reconnected; // let teardown clean up the live session + + // The "connected" notification still fires immediately on reconnect (we suppress the disconnect only). + await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> + verify(notificationRuleProcessor, atLeastOnce()).process(argThat(edgeConnectionTrigger(true)))); + + // Wait until the original disconnect-notification window has fully elapsed... + TimeUnit.MILLISECONDS.sleep(DELAY_MS + 1000); + + // ...the "disconnected" notification must have never been sent. + verify(notificationRuleProcessor, never()).process(argThat(edgeConnectionTrigger(false))); + } + + private ArgumentMatcher edgeConnectionTrigger(boolean connected) { + return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger + && edge.getId().equals(edgeTrigger.getEdgeId()) + && edgeTrigger.isConnected() == connected; + } + +} From 4993ffc66f4749d2465730b498b9f3ea5b5a4131 Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Mon, 8 Jun 2026 17:07:28 +0300 Subject: [PATCH 002/213] refactor: address PR #15732 review - cancel helper, pooled executor, test coverage --- .../service/edge/rpc/EdgeGrpcService.java | 36 +++++++---- .../src/main/resources/thingsboard.yml | 2 +- .../server/edge/AbstractEdgeTest.java | 14 +++- .../edge/EdgeConnectionNotificationTest.java | 6 +- ...geImmediateDisconnectNotificationTest.java | 64 +++++++++++++++++++ 5 files changed, 99 insertions(+), 23 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 7f57101205..a1910396dc 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -36,6 +36,7 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; +import org.thingsboard.server.cache.TbCacheValueWrapper; import org.thingsboard.server.cache.TbTransactionalCache; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.AttributeScope; @@ -242,11 +243,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i sessionEdgeEventChecks.remove(edgeId); } } - pendingDisconnectNotifications.values().forEach(task -> { - if (task != null && !task.isDone()) { - task.cancel(false); - } - }); + pendingDisconnectNotifications.values().forEach(EdgeGrpcService::cancelIfPending); pendingDisconnectNotifications.clear(); if (edgeEventProcessingExecutorService != null) { edgeEventProcessingExecutorService.shutdownNow(); @@ -330,9 +327,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - cancelPendingDisconnectNotification(edgeId); cancelScheduleEdgeEventsCheck(edgeId); } + cancelPendingDisconnectNotification(edgeId); } private void onEdgeEventUpdate(TenantId tenantId, EdgeId edgeId) { @@ -576,7 +573,17 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - edgeIdServiceIdCache.evict(edgeId); + evictServiceIdCacheIfOwnedByThisNode(edgeId); + } + + // Only evict if the cache still points to this node. If the edge already reconnected to a different + // TB-Core node within the keep-alive window, that node has overwritten the entry - evicting it here + // would wipe the live owner and make fireDelayedDisconnectNotification raise a false 'disconnected'. + private void evictServiceIdCacheIfOwnedByThisNode(EdgeId edgeId) { + TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); + if (wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get())) { + edgeIdServiceIdCache.evict(edgeId); + } } private void destroySession(EdgeGrpcSession session) { @@ -710,10 +717,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } EdgeId edgeId = edge.getId(); pendingDisconnectNotifications.compute(edgeId, (id, existing) -> { - if (existing != null && !existing.isDone()) { - existing.cancel(false); - } - return executorService.schedule(() -> fireDelayedDisconnectNotification(tenantId, edge), + cancelIfPending(existing); + return edgeEventProcessingExecutorService.schedule(() -> fireDelayedDisconnectNotification(tenantId, edge), disconnectNotificationDelayMs, TimeUnit.MILLISECONDS); }); } @@ -731,9 +736,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } private void cancelPendingDisconnectNotification(EdgeId edgeId) { - ScheduledFuture pending = pendingDisconnectNotifications.remove(edgeId); - if (pending != null && !pending.isDone()) { - pending.cancel(false); + cancelIfPending(pendingDisconnectNotifications.remove(edgeId)); + } + + private static void cancelIfPending(ScheduledFuture future) { + if (future != null && !future.isDone()) { + future.cancel(false); } } diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 0cb3e57ae8..07ea4dbf06 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1646,7 +1646,7 @@ edges: # Delay (ms) before sending an edge "disconnected" notification. Suppressed if the edge reconnects within # this window - debounces flapping edges from spamming the notification center. Only the notification is # delayed; rule-engine events and state attributes update immediately. Set to 0 to notify immediately. - disconnect_notification_delay_ms: "${TB_EDGE_DISCONNECT_NOTIFICATION_DELAY_MS:60000}" + disconnect_notification_delay_ms: "${EDGES_DISCONNECT_NOTIFICATION_DELAY_MS:60000}" stats: # Enable or disable reporting of edge communication stats (true or false) enabled: "${EDGES_STATS_ENABLED:true}" diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index d75c7b8f59..71802468ab 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -125,6 +125,7 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { public static final String EDGE_HOST = "localhost"; public static final int EDGE_PORT = TestSocketUtils.findAvailableTcpPort(); + @DynamicPropertySource static void props(DynamicPropertyRegistry registry) { log.debug("edges.rpc.port = {}", EDGE_PORT); @@ -157,16 +158,23 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { //8 installation messages installation(); - edgeImitator = new EdgeImitator(EDGE_HOST, EDGE_PORT, edge.getRoutingKey(), edge.getSecret()); + edgeImitator = createEdgeImitator(); // 17 connect messages + 8 installation messages edgeImitator.expectMessageAmount(SYNC_MESSAGE_COUNT); - edgeImitator.ignoreType(OAuth2ClientUpdateMsg.class); - edgeImitator.ignoreType(OAuth2DomainUpdateMsg.class); edgeImitator.connect(); verifyEdgeConnectionAndInitialData(); } + // Creates an EdgeImitator wired with the standard ignored message types, but not yet connected. + // Callers add any expectations (e.g. expectMessageAmount) before invoking connect() themselves. + protected EdgeImitator createEdgeImitator() throws Exception { + EdgeImitator imitator = new EdgeImitator(EDGE_HOST, EDGE_PORT, edge.getRoutingKey(), edge.getSecret()); + imitator.ignoreType(OAuth2ClientUpdateMsg.class); + imitator.ignoreType(OAuth2DomainUpdateMsg.class); + return imitator; + } + @After public void teardownEdgeTest() { try { diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java index f72ad51f4a..8179e5894a 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java @@ -25,8 +25,6 @@ import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.controller.AbstractWebTest; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; -import org.thingsboard.server.gen.edge.v1.OAuth2ClientUpdateMsg; -import org.thingsboard.server.gen.edge.v1.OAuth2DomainUpdateMsg; import java.util.concurrent.TimeUnit; @@ -70,9 +68,7 @@ public class EdgeConnectionNotificationTest extends AbstractEdgeTest { TimeUnit.SECONDS.sleep(1); // ...and reconnects within the delay window, which must cancel the pending "disconnected" notification. - EdgeImitator reconnected = new EdgeImitator(EDGE_HOST, EDGE_PORT, edge.getRoutingKey(), edge.getSecret()); - reconnected.ignoreType(OAuth2ClientUpdateMsg.class); - reconnected.ignoreType(OAuth2DomainUpdateMsg.class); + EdgeImitator reconnected = createEdgeImitator(); reconnected.connect(); edgeImitator = reconnected; // let teardown clean up the live session diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java new file mode 100644 index 0000000000..a9d6dbe455 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.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.edge; + +import org.junit.Test; +import org.mockito.ArgumentMatcher; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; +import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.controller.AbstractWebTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +// Covers the disconnect_notification_delay_ms <= 0 branch in EdgeGrpcService.scheduleDisconnectNotification, +// where the "disconnected" notification must be sent immediately instead of being scheduled with a delay. +@DaoSqlTest +@TestPropertySource(properties = { + "edges.connectivity.disconnect_notification_delay_ms=0" +}) +public class EdgeImmediateDisconnectNotificationTest extends AbstractEdgeTest { + + @MockitoSpyBean + private NotificationRuleProcessor notificationRuleProcessor; + + @Test + public void givenZeroDelay_whenEdgeDisconnects_thenDisconnectNotificationSentImmediately() throws Exception { + clearInvocations(notificationRuleProcessor); + + edgeImitator.disconnect(); + + // With a zero delay there is no debounce window - the "disconnected" notification fires right away. + await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> + verify(notificationRuleProcessor, times(1)).process(argThat(edgeConnectionTrigger()))); + } + + private ArgumentMatcher edgeConnectionTrigger() { + return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger + && edge.getId().equals(edgeTrigger.getEdgeId()) + && !edgeTrigger.isConnected(); + } + +} From f10ca1338c99c22148bad5a026435e916bb69be3 Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Wed, 10 Jun 2026 16:34:02 +0300 Subject: [PATCH 003/213] removeOnCancelPolicy, cluster-path unit test, cleanups --- .../service/edge/rpc/EdgeGrpcService.java | 90 +++++--- .../server/edge/AbstractEdgeTest.java | 1 - .../edge/EdgeConnectionNotificationTest.java | 56 ++++- ...geImmediateDisconnectNotificationTest.java | 64 ------ .../service/edge/rpc/EdgeGrpcServiceTest.java | 204 ++++++++++++++++++ .../common/util/ThingsBoardExecutors.java | 10 +- 6 files changed, 317 insertions(+), 108 deletions(-) delete mode 100644 application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index a1910396dc..b875226034 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -69,6 +69,7 @@ import org.thingsboard.server.queue.provider.TbCoreQueueFactory; import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import java.io.IOException; import java.util.ArrayList; @@ -103,7 +104,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private final ConcurrentMap sessionNewEventsLocks = new ConcurrentHashMap<>(); private final Map sessionNewEvents = new HashMap<>(); private final ConcurrentMap> sessionEdgeEventChecks = new ConcurrentHashMap<>(); - private final ConcurrentMap> pendingDisconnectNotifications = new ConcurrentHashMap<>(); + private final ConcurrentMap pendingDisconnectNotifications = new ConcurrentHashMap<>(); private final ConcurrentMap> localSyncEdgeRequests = new ConcurrentHashMap<>(); private final ConcurrentMap edgeEventsMigrationProcessed = new ConcurrentHashMap<>(); private final List zombieSessions = new ArrayList<>(); @@ -144,6 +145,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Lazy private EdgeContextComponent ctx; + @Autowired + private TelemetrySubscriptionService tsSubService; + @Autowired private TbClusterService clusterService; @@ -198,7 +202,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } this.edgeEventProcessingExecutorService = ThingsBoardExecutors.newScheduledThreadPool(schedulerPoolSize, "edge-event-check-scheduler"); this.sendDownlinkExecutorService = ThingsBoardExecutors.newScheduledThreadPool(sendSchedulerPoolSize, "edge-send-scheduler"); - this.executorService = ThingsBoardExecutors.newSingleThreadScheduledExecutor("edge-service"); + // removeOnCancelPolicy: cancelled delayed disconnect notifications (common with flapping edges) are dropped + // from the queue right away on reconnect, instead of piling up until their original fire time. + this.executorService = ThingsBoardExecutors.newSingleThreadScheduledExecutor("edge-service", true); this.executorService.scheduleAtFixedRate(this::cleanupZombieSessions, 60, 60, TimeUnit.SECONDS); log.info("Edge RPC service initialized!"); } @@ -232,19 +238,23 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @PreDestroy public void destroy() { + // Flush already-pending disconnect notifications BEFORE shutting the server down. These are edges that + // disconnected on their own within the delay window; without this a graceful restart would silently + // swallow their "disconnected" alert. Snapshotting first means we only flush those - not edges that this + // very shutdown is about to disconnect (they rebalance to another node and shouldn't alert) - and we run + // while the scheduler and rule engine are still alive. The guard inside fireDelayedDisconnectNotification + // still suppresses any edge that reconnected elsewhere. + List pendingToFlush = new ArrayList<>(pendingDisconnectNotifications.values()); + pendingDisconnectNotifications.clear(); + pendingToFlush.forEach(pending -> { + cancelIfPending(pending.future()); + fireDelayedDisconnectNotification(pending); + }); if (server != null) { server.shutdownNow(); } - for (Map.Entry> entry : sessionEdgeEventChecks.entrySet()) { - EdgeId edgeId = entry.getKey(); - ScheduledFuture sessionEdgeEventCheck = entry.getValue(); - if (sessionEdgeEventCheck != null && !sessionEdgeEventCheck.isCancelled() && !sessionEdgeEventCheck.isDone()) { - sessionEdgeEventCheck.cancel(true); - sessionEdgeEventChecks.remove(edgeId); - } - } - pendingDisconnectNotifications.values().forEach(EdgeGrpcService::cancelIfPending); - pendingDisconnectNotifications.clear(); + sessionEdgeEventChecks.values().forEach(task -> cancelIfPending(task, true)); + sessionEdgeEventChecks.clear(); if (edgeEventProcessingExecutorService != null) { edgeEventProcessingExecutorService.shutdownNow(); } @@ -393,6 +403,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // If the edge reconnected within the disconnect-notification delay window, suppress the pending // "disconnected" notification - the drop was transient (debounce for flapping edges). cancelPendingDisconnectNotification(edgeId); + // Connect notifies immediately; only the disconnect notification is debounced (see scheduleDisconnectNotification). pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); notifyEdgeConnectivity(tenantId, edge, true); cancelScheduleEdgeEventsCheck(edgeId); @@ -528,13 +539,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cancelScheduleEdgeEventsCheck(EdgeId edgeId) { log.trace("[{}] cancelling edge event check for edge", edgeId); - if (sessionEdgeEventChecks.containsKey(edgeId)) { - ScheduledFuture sessionEdgeEventCheck = sessionEdgeEventChecks.get(edgeId); - if (sessionEdgeEventCheck != null && !sessionEdgeEventCheck.isCancelled() && !sessionEdgeEventCheck.isDone()) { - sessionEdgeEventCheck.cancel(true); - sessionEdgeEventChecks.remove(edgeId); - } - } + cancelIfPending(sessionEdgeEventChecks.remove(edgeId), true); } private void onEdgeDisconnect(Edge edge, UUID sessionId) { @@ -602,14 +607,14 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void save(TenantId tenantId, EdgeId edgeId, String key, long value) { log.debug("[{}][{}] Updating long edge telemetry [{}] [{}]", tenantId, edgeId, key, value); if (persistToTelemetry) { - ctx.getTsSubService().saveTimeseries(TimeseriesSaveRequest.builder() + tsSubService.saveTimeseries(TimeseriesSaveRequest.builder() .tenantId(tenantId) .entityId(edgeId) .entry(new LongDataEntry(key, value)) .callback(new AttributeSaveCallback(tenantId, edgeId, key, value)) .build()); } else { - ctx.getTsSubService().saveAttributes(AttributesSaveRequest.builder() + tsSubService.saveAttributes(AttributesSaveRequest.builder() .tenantId(tenantId) .entityId(edgeId) .scope(AttributeScope.SERVER_SCOPE) @@ -622,14 +627,14 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void save(TenantId tenantId, EdgeId edgeId, String key, boolean value) { log.debug("[{}][{}] Updating boolean edge telemetry [{}] [{}]", tenantId, edgeId, key, value); if (persistToTelemetry) { - ctx.getTsSubService().saveTimeseries(TimeseriesSaveRequest.builder() + tsSubService.saveTimeseries(TimeseriesSaveRequest.builder() .tenantId(tenantId) .entityId(edgeId) .entry(new BooleanDataEntry(key, value)) .callback(new AttributeSaveCallback(tenantId, edgeId, key, value)) .build()); } else { - ctx.getTsSubService().saveAttributes(AttributesSaveRequest.builder() + tsSubService.saveAttributes(AttributesSaveRequest.builder() .tenantId(tenantId) .entityId(edgeId) .scope(AttributeScope.SERVER_SCOPE) @@ -717,31 +722,51 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } EdgeId edgeId = edge.getId(); pendingDisconnectNotifications.compute(edgeId, (id, existing) -> { - cancelIfPending(existing); - return edgeEventProcessingExecutorService.schedule(() -> fireDelayedDisconnectNotification(tenantId, edge), + if (existing != null) { + cancelIfPending(existing.future()); + } + // Single-element holder so the scheduled task can reference its own pending entry, which doesn't exist + // until schedule(...) returns. The task needs it for the identity-keyed remove in fireDelayedDisconnectNotification. + PendingDisconnect[] holder = {null}; + ScheduledFuture future = executorService.schedule( + () -> fireDelayedDisconnectNotification(holder[0]), disconnectNotificationDelayMs, TimeUnit.MILLISECONDS); + holder[0] = new PendingDisconnect(tenantId, edge, future); + return holder[0]; }); } - private void fireDelayedDisconnectNotification(TenantId tenantId, Edge edge) { - EdgeId edgeId = edge.getId(); - pendingDisconnectNotifications.remove(edgeId); + private void fireDelayedDisconnectNotification(PendingDisconnect pending) { + EdgeId edgeId = pending.edge().getId(); + // Identity-keyed remove: don't clobber a newer entry if a second disconnect races with this task firing. + pendingDisconnectNotifications.remove(edgeId, pending); // Re-verify the edge is still disconnected. The cache is cluster-wide, so this also covers the case // where the edge dropped on this node and reconnected to a different TB-Core node within the window. if (sessions.containsKey(edgeId) || edgeIdServiceIdCache.get(edgeId) != null) { - log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", tenantId, edgeId); + log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", pending.tenantId(), edgeId); return; } - notifyEdgeConnectivity(tenantId, edge, false); + notifyEdgeConnectivity(pending.tenantId(), pending.edge(), false); } private void cancelPendingDisconnectNotification(EdgeId edgeId) { - cancelIfPending(pendingDisconnectNotifications.remove(edgeId)); + PendingDisconnect pending = pendingDisconnectNotifications.remove(edgeId); + if (pending != null) { + cancelIfPending(pending.future()); + } } + // Carries the context the delayed task needs, so a pending notification can still be fired on shutdown + // (see destroy()), not just cancelled. Package-private for unit testing of fireDelayedDisconnectNotification. + record PendingDisconnect(TenantId tenantId, Edge edge, ScheduledFuture future) {} + private static void cancelIfPending(ScheduledFuture future) { + cancelIfPending(future, false); + } + + private static void cancelIfPending(ScheduledFuture future, boolean mayInterruptIfRunning) { if (future != null && !future.isDone()) { - future.cancel(false); + future.cancel(mayInterruptIfRunning); } } @@ -797,6 +822,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i !kafkaSession.getConsumer().getConsumer().isStopped(); } return false; + } } diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index 71802468ab..8a3c3c1ae7 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -125,7 +125,6 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { public static final String EDGE_HOST = "localhost"; public static final int EDGE_PORT = TestSocketUtils.findAvailableTcpPort(); - @DynamicPropertySource static void props(DynamicPropertyRegistry registry) { log.debug("edges.rpc.port = {}", EDGE_PORT); diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java index 8179e5894a..c46d82437a 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java @@ -15,16 +15,20 @@ */ package org.thingsboard.server.edge; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; -import org.springframework.test.context.TestPropertySource; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.controller.AbstractWebTest; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; +import org.thingsboard.server.service.edge.rpc.EdgeGrpcService; import java.util.concurrent.TimeUnit; @@ -37,9 +41,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @DaoSqlTest -@TestPropertySource(properties = { - "edges.connectivity.disconnect_notification_delay_ms=5000" -}) public class EdgeConnectionNotificationTest extends AbstractEdgeTest { private static final long DELAY_MS = 5000L; @@ -47,19 +48,55 @@ public class EdgeConnectionNotificationTest extends AbstractEdgeTest { @MockitoSpyBean private NotificationRuleProcessor notificationRuleProcessor; + @Autowired + private EdgeGrpcService edgeGrpcService; + + private long originalDisconnectNotificationDelayMs; + + // Capture the bean's configured delay before each test and restore it after, so a test method that forgets + // to call setDisconnectNotificationDelayMs can't silently inherit the previous method's mutated value + // (the shared context means the mutation would otherwise persist across methods). + @Before + public void captureDisconnectNotificationDelay() { + originalDisconnectNotificationDelayMs = (long) ReflectionTestUtils.getField(edgeGrpcService, "disconnectNotificationDelayMs"); + } + + @After + public void restoreDisconnectNotificationDelay() { + setDisconnectNotificationDelayMs(originalDisconnectNotificationDelayMs); + } + + // The delay is overridden per test (rather than via a per-class @TestPropertySource) so all cases share a + // single Spring application context instead of booting a separate heavy context per delay value. + private void setDisconnectNotificationDelayMs(long delayMs) { + ReflectionTestUtils.setField(edgeGrpcService, "disconnectNotificationDelayMs", delayMs); + } + @Test public void givenEdgeStaysDisconnected_whenDelayElapses_thenDisconnectNotificationSent() throws Exception { + // After the configured delay, the "disconnected" notification is sent exactly once. + assertDisconnectNotificationSentOnce(DELAY_MS); + } + + @Test + public void givenZeroDelay_whenEdgeDisconnects_thenDisconnectNotificationSentImmediately() throws Exception { + // With a zero delay there is no debounce window - the "disconnected" notification fires right away. + assertDisconnectNotificationSentOnce(0); + } + + private void assertDisconnectNotificationSentOnce(long delayMs) throws Exception { + setDisconnectNotificationDelayMs(delayMs); clearInvocations(notificationRuleProcessor); edgeImitator.disconnect(); - // After the configured delay, the "disconnected" notification is sent exactly once. await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> verify(notificationRuleProcessor, times(1)).process(argThat(edgeConnectionTrigger(false)))); } @Test public void givenEdgeReconnectsWithinDelay_whenEdgeFlaps_thenDisconnectNotificationSuppressed() throws Exception { + setDisconnectNotificationDelayMs(DELAY_MS); clearInvocations(notificationRuleProcessor); // Edge drops... @@ -76,11 +113,10 @@ public class EdgeConnectionNotificationTest extends AbstractEdgeTest { await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> verify(notificationRuleProcessor, atLeastOnce()).process(argThat(edgeConnectionTrigger(true)))); - // Wait until the original disconnect-notification window has fully elapsed... - TimeUnit.MILLISECONDS.sleep(DELAY_MS + 1000); - - // ...the "disconnected" notification must have never been sent. - verify(notificationRuleProcessor, never()).process(argThat(edgeConnectionTrigger(false))); + // The "disconnected" notification must never be sent throughout the full delay window. + await().during(DELAY_MS + 500, TimeUnit.MILLISECONDS) + .atMost(DELAY_MS + 2000, TimeUnit.MILLISECONDS) + .untilAsserted(() -> verify(notificationRuleProcessor, never()).process(argThat(edgeConnectionTrigger(false)))); } private ArgumentMatcher edgeConnectionTrigger(boolean connected) { diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java deleted file mode 100644 index a9d6dbe455..0000000000 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeImmediateDisconnectNotificationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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.edge; - -import org.junit.Test; -import org.mockito.ArgumentMatcher; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; -import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; -import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; -import org.thingsboard.server.controller.AbstractWebTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -import java.util.concurrent.TimeUnit; - -import static org.awaitility.Awaitility.await; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.clearInvocations; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -// Covers the disconnect_notification_delay_ms <= 0 branch in EdgeGrpcService.scheduleDisconnectNotification, -// where the "disconnected" notification must be sent immediately instead of being scheduled with a delay. -@DaoSqlTest -@TestPropertySource(properties = { - "edges.connectivity.disconnect_notification_delay_ms=0" -}) -public class EdgeImmediateDisconnectNotificationTest extends AbstractEdgeTest { - - @MockitoSpyBean - private NotificationRuleProcessor notificationRuleProcessor; - - @Test - public void givenZeroDelay_whenEdgeDisconnects_thenDisconnectNotificationSentImmediately() throws Exception { - clearInvocations(notificationRuleProcessor); - - edgeImitator.disconnect(); - - // With a zero delay there is no debounce window - the "disconnected" notification fires right away. - await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> - verify(notificationRuleProcessor, times(1)).process(argThat(edgeConnectionTrigger()))); - } - - private ArgumentMatcher edgeConnectionTrigger() { - return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger - && edge.getId().equals(edgeTrigger.getEdgeId()) - && !edgeTrigger.isConnected(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java new file mode 100644 index 0000000000..f538bd1baa --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -0,0 +1,204 @@ +/** + * 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.service.edge.rpc; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; +import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.rule.trigger.EdgeConnectionTrigger; +import org.thingsboard.server.common.data.notification.rule.trigger.NotificationRuleTrigger; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; + +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Unit coverage for the cluster-aware predicates that guard the delayed disconnect notification: + * {@code evictServiceIdCacheIfOwnedByThisNode} and the re-verify check in + * {@code fireDelayedDisconnectNotification}. These exercise the cross-node ownership logic that the + * single-node integration tests ({@code EdgeConnectionNotificationTest}) cannot reach. + */ +@ExtendWith(MockitoExtension.class) +public class EdgeGrpcServiceTest { + + private static final String THIS_NODE = "tb-core-1"; + private static final String OTHER_NODE = "tb-core-2"; + + @Mock + private TbTransactionalCache edgeIdServiceIdCache; + + @Mock + private TbServiceInfoProvider serviceInfoProvider; + + @Mock + private EdgeContextComponent ctx; + + @Mock + private NotificationRuleProcessor ruleProcessor; + + @InjectMocks + private EdgeGrpcService edgeGrpcService; + + private TenantId tenantId; + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + public void setUp() { + tenantId = new TenantId(UUID.randomUUID()); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(tenantId); + edge.setName("test-edge"); + } + + // --- evictServiceIdCacheIfOwnedByThisNode --- + + @Test + public void givenCacheOwnedByThisNode_whenEvict_thenEntryIsEvicted() { + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + + evictServiceIdCacheIfOwnedByThisNode(); + + verify(edgeIdServiceIdCache, times(1)).evict(edgeId); + } + + @Test + public void givenCacheOwnedByAnotherNode_whenEvict_thenEntryIsKept() { + // The edge already reconnected to another node within the keep-alive window: must NOT wipe the live owner. + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); + + evictServiceIdCacheIfOwnedByThisNode(); + + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + public void givenEmptyCache_whenEvict_thenNothingEvicted() { + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); + + evictServiceIdCacheIfOwnedByThisNode(); + + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + // --- fireDelayedDisconnectNotification re-verify guard --- + + @Test + public void givenEdgeReconnectedToThisNode_whenDelayFires_thenNotificationSuppressed() { + // A live session exists again on this node - suppress the stale disconnect notification. + sessions().put(edgeId, mock(EdgeGrpcSession.class)); + + fireDelayedDisconnectNotification(); + + verify(ruleProcessor, never()).process(any()); + } + + @Test + public void givenEdgeReconnectedToAnotherNode_whenDelayFires_thenNotificationSuppressed() { + // No local session, but the cluster cache still points at some node: the edge is connected elsewhere. + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); + + fireDelayedDisconnectNotification(); + + verify(ruleProcessor, never()).process(any()); + } + + @Test + public void givenEdgeStaysDisconnectedClusterWide_whenDelayFires_thenNotificationSent() { + // No local session and no cache entry on any node: the edge is genuinely down - fire the notification. + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + + fireDelayedDisconnectNotification(); + + verify(ruleProcessor, times(1)).process(argThat(disconnectTrigger())); + } + + @Test + public void givenPendingDisconnect_whenDestroy_thenNotificationFlushed() { + // The edge is genuinely down (no session, no cache). A graceful shutdown must flush the pending + // notification rather than drop it, otherwise a restart within the delay window swallows the alert. + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(tenantId, edge, null)); + + destroy(); + + verify(ruleProcessor, times(1)).process(argThat(disconnectTrigger())); + } + + @Test + public void givenPendingDisconnectButReconnectedElsewhere_whenDestroy_thenNotificationSuppressed() { + // The flush still honors the re-verify guard: an edge that reconnected to another node must not alert. + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); + pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(tenantId, edge, null)); + + destroy(); + + verify(ruleProcessor, never()).process(any()); + } + + private void destroy() { + ReflectionTestUtils.invokeMethod(edgeGrpcService, "destroy"); + } + + private void evictServiceIdCacheIfOwnedByThisNode() { + ReflectionTestUtils.invokeMethod(edgeGrpcService, "evictServiceIdCacheIfOwnedByThisNode", edgeId); + } + + private void fireDelayedDisconnectNotification() { + EdgeGrpcService.PendingDisconnect pending = new EdgeGrpcService.PendingDisconnect(tenantId, edge, null); + ReflectionTestUtils.invokeMethod(edgeGrpcService, "fireDelayedDisconnectNotification", pending); + } + + @SuppressWarnings("unchecked") + private ConcurrentMap sessions() { + return (ConcurrentMap) ReflectionTestUtils.getField(edgeGrpcService, "sessions"); + } + + @SuppressWarnings("unchecked") + private ConcurrentMap pendingDisconnects() { + return (ConcurrentMap) ReflectionTestUtils.getField(edgeGrpcService, "pendingDisconnectNotifications"); + } + + private static ArgumentMatcher disconnectTrigger() { + return trigger -> trigger instanceof EdgeConnectionTrigger edgeTrigger && !edgeTrigger.isConnected(); + } + +} diff --git a/common/util/src/main/java/org/thingsboard/common/util/ThingsBoardExecutors.java b/common/util/src/main/java/org/thingsboard/common/util/ThingsBoardExecutors.java index 71b4925901..47934b4df0 100644 --- a/common/util/src/main/java/org/thingsboard/common/util/ThingsBoardExecutors.java +++ b/common/util/src/main/java/org/thingsboard/common/util/ThingsBoardExecutors.java @@ -69,7 +69,15 @@ public class ThingsBoardExecutors { } public static ScheduledExecutorService newSingleThreadScheduledExecutor(String name) { - return Executors.unconfigurableScheduledExecutorService(new ThingsBoardScheduledThreadPoolExecutor(1, ThingsBoardThreadFactory.forName(name))); + return newSingleThreadScheduledExecutor(name, false); + } + + public static ScheduledExecutorService newSingleThreadScheduledExecutor(String name, boolean removeOnCancelPolicy) { + ThingsBoardScheduledThreadPoolExecutor executor = new ThingsBoardScheduledThreadPoolExecutor(1, ThingsBoardThreadFactory.forName(name)); + // Must be set before wrapping: unconfigurableScheduledExecutorService hides the setter. With it enabled, + // cancelled tasks are removed from the delay queue immediately instead of lingering until their fire time. + executor.setRemoveOnCancelPolicy(removeOnCancelPolicy); + return Executors.unconfigurableScheduledExecutorService(executor); } public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String name) { From 44ea99b1e199af49a9d1947ad2dbe2e32340e93c Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Wed, 10 Jun 2026 17:20:19 +0300 Subject: [PATCH 004/213] guard cache evict, drop holder array, derive tenant from edge --- .../service/edge/rpc/EdgeGrpcService.java | 65 +++++++++++++------ .../service/edge/rpc/EdgeGrpcServiceTest.java | 6 +- 2 files changed, 49 insertions(+), 22 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index b875226034..259f63c206 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -405,7 +405,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i cancelPendingDisconnectNotification(edgeId); // Connect notifies immediately; only the disconnect notification is debounced (see scheduleDisconnectNotification). pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); - notifyEdgeConnectivity(tenantId, edge, true); + notifyEdgeConnectivity(edge, true); cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); @@ -562,7 +562,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i long lastDisconnectTs = System.currentTimeMillis(); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - scheduleDisconnectNotification(tenantId, edge); + scheduleDisconnectNotification(edge); cancelScheduleEdgeEventsCheck(edgeId); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -578,7 +578,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - evictServiceIdCacheIfOwnedByThisNode(edgeId); + // Don't evict while a live session for this edge still exists on this node (e.g. a stale session + // disconnecting after a newer one already replaced it) - that newer session legitimately owns the + // cache entry, and wiping it would let another node's pending task fire a false 'disconnected' notification. + if (!sessions.containsKey(edgeId)) { + evictServiceIdCacheIfOwnedByThisNode(edgeId); + } } // Only evict if the cache still points to this node. If the edge already reconnected to a different @@ -702,22 +707,22 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } } - private void notifyEdgeConnectivity(TenantId tenantId, Edge edge, boolean connected) { + private void notifyEdgeConnectivity(Edge edge, boolean connected) { try { ctx.getRuleProcessor().process(EdgeConnectionTrigger.builder() - .tenantId(tenantId) + .tenantId(edge.getTenantId()) .customerId(edge.getCustomerId()) .edgeId(edge.getId()) .edgeName(edge.getName()) .connected(connected).build()); } catch (Exception e) { - log.warn("[{}][{}] Failed to process edge connectivity notification (connected={})", tenantId, edge.getId(), connected, e); + log.warn("[{}][{}] Failed to process edge connectivity notification (connected={})", edge.getTenantId(), edge.getId(), connected, e); } } - private void scheduleDisconnectNotification(TenantId tenantId, Edge edge) { + private void scheduleDisconnectNotification(Edge edge) { if (disconnectNotificationDelayMs <= 0) { - notifyEdgeConnectivity(tenantId, edge, false); + notifyEdgeConnectivity(edge, false); return; } EdgeId edgeId = edge.getId(); @@ -725,28 +730,30 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i if (existing != null) { cancelIfPending(existing.future()); } - // Single-element holder so the scheduled task can reference its own pending entry, which doesn't exist - // until schedule(...) returns. The task needs it for the identity-keyed remove in fireDelayedDisconnectNotification. - PendingDisconnect[] holder = {null}; + // Create the pending entry first so the scheduled task can reference it (for the identity-keyed + // remove in fireDelayedDisconnectNotification), then back-fill its future. Doing this inside compute() + // keeps it under the map bin lock, so the future is set before the entry becomes visible to other threads. + PendingDisconnect pending = new PendingDisconnect(edge); ScheduledFuture future = executorService.schedule( - () -> fireDelayedDisconnectNotification(holder[0]), + () -> fireDelayedDisconnectNotification(pending), disconnectNotificationDelayMs, TimeUnit.MILLISECONDS); - holder[0] = new PendingDisconnect(tenantId, edge, future); - return holder[0]; + pending.setFuture(future); + return pending; }); } private void fireDelayedDisconnectNotification(PendingDisconnect pending) { - EdgeId edgeId = pending.edge().getId(); + Edge edge = pending.edge(); + EdgeId edgeId = edge.getId(); // Identity-keyed remove: don't clobber a newer entry if a second disconnect races with this task firing. pendingDisconnectNotifications.remove(edgeId, pending); // Re-verify the edge is still disconnected. The cache is cluster-wide, so this also covers the case // where the edge dropped on this node and reconnected to a different TB-Core node within the window. if (sessions.containsKey(edgeId) || edgeIdServiceIdCache.get(edgeId) != null) { - log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", pending.tenantId(), edgeId); + log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", edge.getTenantId(), edgeId); return; } - notifyEdgeConnectivity(pending.tenantId(), pending.edge(), false); + notifyEdgeConnectivity(edge, false); } private void cancelPendingDisconnectNotification(EdgeId edgeId) { @@ -757,8 +764,28 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } // Carries the context the delayed task needs, so a pending notification can still be fired on shutdown - // (see destroy()), not just cancelled. Package-private for unit testing of fireDelayedDisconnectNotification. - record PendingDisconnect(TenantId tenantId, Edge edge, ScheduledFuture future) {} + // (see destroy()), not just cancelled. The future is back-filled right after scheduling (see + // scheduleDisconnectNotification). Package-private for unit testing of fireDelayedDisconnectNotification. + static final class PendingDisconnect { + private final Edge edge; + private ScheduledFuture future; + + PendingDisconnect(Edge edge) { + this.edge = edge; + } + + Edge edge() { + return edge; + } + + ScheduledFuture future() { + return future; + } + + void setFuture(ScheduledFuture future) { + this.future = future; + } + } private static void cancelIfPending(ScheduledFuture future) { cancelIfPending(future, false); diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index f538bd1baa..86758cb68f 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -156,7 +156,7 @@ public class EdgeGrpcServiceTest { // notification rather than drop it, otherwise a restart within the delay window swallows the alert. when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); - pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(tenantId, edge, null)); + pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(edge)); destroy(); @@ -167,7 +167,7 @@ public class EdgeGrpcServiceTest { public void givenPendingDisconnectButReconnectedElsewhere_whenDestroy_thenNotificationSuppressed() { // The flush still honors the re-verify guard: an edge that reconnected to another node must not alert. when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); - pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(tenantId, edge, null)); + pendingDisconnects().put(edgeId, new EdgeGrpcService.PendingDisconnect(edge)); destroy(); @@ -183,7 +183,7 @@ public class EdgeGrpcServiceTest { } private void fireDelayedDisconnectNotification() { - EdgeGrpcService.PendingDisconnect pending = new EdgeGrpcService.PendingDisconnect(tenantId, edge, null); + EdgeGrpcService.PendingDisconnect pending = new EdgeGrpcService.PendingDisconnect(edge); ReflectionTestUtils.invokeMethod(edgeGrpcService, "fireDelayedDisconnectNotification", pending); } From 9fdb32da0568c57e2930edbf98fd1a591a4c50ea Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Wed, 10 Jun 2026 17:59:08 +0300 Subject: [PATCH 005/213] refactor: tidy edge disconnect-notification per review --- .../service/edge/rpc/EdgeGrpcService.java | 31 +++++++++---------- .../edge/EdgeConnectionNotificationTest.java | 6 ++-- .../service/edge/rpc/EdgeGrpcServiceTest.java | 12 +------ 3 files changed, 19 insertions(+), 30 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 259f63c206..411ccd5f05 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -238,18 +238,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @PreDestroy public void destroy() { - // Flush already-pending disconnect notifications BEFORE shutting the server down. These are edges that - // disconnected on their own within the delay window; without this a graceful restart would silently - // swallow their "disconnected" alert. Snapshotting first means we only flush those - not edges that this - // very shutdown is about to disconnect (they rebalance to another node and shouldn't alert) - and we run - // while the scheduler and rule engine are still alive. The guard inside fireDelayedDisconnectNotification - // still suppresses any edge that reconnected elsewhere. List pendingToFlush = new ArrayList<>(pendingDisconnectNotifications.values()); pendingDisconnectNotifications.clear(); - pendingToFlush.forEach(pending -> { - cancelIfPending(pending.future()); - fireDelayedDisconnectNotification(pending); - }); + pendingToFlush.forEach(this::fireDelayedDisconnectNotification); if (server != null) { server.shutdownNow(); } @@ -590,12 +581,22 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // TB-Core node within the keep-alive window, that node has overwritten the entry - evicting it here // would wipe the live owner and make fireDelayedDisconnectNotification raise a false 'disconnected'. private void evictServiceIdCacheIfOwnedByThisNode(EdgeId edgeId) { - TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); - if (wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get())) { + if (isOwnedByThisNode(edgeId)) { edgeIdServiceIdCache.evict(edgeId); } } + // The edge's service-id cache entry still points at this node, i.e. this node is the recorded owner. + private boolean isOwnedByThisNode(EdgeId edgeId) { + TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); + return wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get()); + } + + // The edge has a live owner somewhere in the cluster (the cache is cluster-wide), regardless of which node. + private boolean isConnectedClusterWide(EdgeId edgeId) { + return edgeIdServiceIdCache.get(edgeId) != null; + } + private void destroySession(EdgeGrpcSession session) { try (session) { if (!session.destroy()) { @@ -749,7 +750,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i pendingDisconnectNotifications.remove(edgeId, pending); // Re-verify the edge is still disconnected. The cache is cluster-wide, so this also covers the case // where the edge dropped on this node and reconnected to a different TB-Core node within the window. - if (sessions.containsKey(edgeId) || edgeIdServiceIdCache.get(edgeId) != null) { + if (sessions.containsKey(edgeId) || isConnectedClusterWide(edgeId)) { log.debug("[{}][{}] Edge reconnected within the disconnect notification delay - skipping disconnect notification", edge.getTenantId(), edgeId); return; } @@ -763,9 +764,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } } - // Carries the context the delayed task needs, so a pending notification can still be fired on shutdown - // (see destroy()), not just cancelled. The future is back-filled right after scheduling (see - // scheduleDisconnectNotification). Package-private for unit testing of fireDelayedDisconnectNotification. static final class PendingDisconnect { private final Edge edge; private ScheduledFuture future; @@ -785,6 +783,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i void setFuture(ScheduledFuture future) { this.future = future; } + } private static void cancelIfPending(ScheduledFuture future) { diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java index c46d82437a..66023c7372 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify; @DaoSqlTest public class EdgeConnectionNotificationTest extends AbstractEdgeTest { - private static final long DELAY_MS = 5000L; + private static final long DELAY_MS = 1500L; @MockitoSpyBean private NotificationRuleProcessor notificationRuleProcessor; @@ -115,8 +115,8 @@ public class EdgeConnectionNotificationTest extends AbstractEdgeTest { // The "disconnected" notification must never be sent throughout the full delay window. await().during(DELAY_MS + 500, TimeUnit.MILLISECONDS) - .atMost(DELAY_MS + 2000, TimeUnit.MILLISECONDS) - .untilAsserted(() -> verify(notificationRuleProcessor, never()).process(argThat(edgeConnectionTrigger(false)))); + .atMost(DELAY_MS + 2000, TimeUnit.MILLISECONDS) + .untilAsserted(() -> verify(notificationRuleProcessor, never()).process(argThat(edgeConnectionTrigger(false)))); } private ArgumentMatcher edgeConnectionTrigger(boolean connected) { diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 86758cb68f..61bb04a803 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -45,12 +45,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -/** - * Unit coverage for the cluster-aware predicates that guard the delayed disconnect notification: - * {@code evictServiceIdCacheIfOwnedByThisNode} and the re-verify check in - * {@code fireDelayedDisconnectNotification}. These exercise the cross-node ownership logic that the - * single-node integration tests ({@code EdgeConnectionNotificationTest}) cannot reach. - */ @ExtendWith(MockitoExtension.class) public class EdgeGrpcServiceTest { @@ -72,21 +66,17 @@ public class EdgeGrpcServiceTest { @InjectMocks private EdgeGrpcService edgeGrpcService; - private TenantId tenantId; private EdgeId edgeId; private Edge edge; @BeforeEach public void setUp() { - tenantId = new TenantId(UUID.randomUUID()); edgeId = new EdgeId(UUID.randomUUID()); edge = new Edge(edgeId); - edge.setTenantId(tenantId); + edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); edge.setName("test-edge"); } - // --- evictServiceIdCacheIfOwnedByThisNode --- - @Test public void givenCacheOwnedByThisNode_whenEvict_thenEntryIsEvicted() { when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); From 668ca3b632674bc42d1616d4de58d18c5e94be26 Mon Sep 17 00:00:00 2001 From: Andrii Landiak Date: Thu, 11 Jun 2026 10:55:51 +0300 Subject: [PATCH 006/213] Fixes after dev-rereview --- .../service/edge/rpc/EdgeGrpcService.java | 24 +++++++++++++++---- .../edge/EdgeConnectionNotificationTest.java | 9 +++++-- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 411ccd5f05..297a45ec2f 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -84,6 +84,7 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; @@ -722,6 +723,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } private void scheduleDisconnectNotification(Edge edge) { + // Zero delay means "no debounce": notify immediately and skip the cluster-wide re-verify guard. if (disconnectNotificationDelayMs <= 0) { notifyEdgeConnectivity(edge, false); return; @@ -729,7 +731,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = edge.getId(); pendingDisconnectNotifications.compute(edgeId, (id, existing) -> { if (existing != null) { - cancelIfPending(existing.future()); + cancelIfPending(existing.getFuture()); } // Create the pending entry first so the scheduled task can reference it (for the identity-keyed // remove in fireDelayedDisconnectNotification), then back-fill its future. Doing this inside compute() @@ -744,7 +746,13 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } private void fireDelayedDisconnectNotification(PendingDisconnect pending) { - Edge edge = pending.edge(); + // Claim-once guard: the @PreDestroy destroy() flush and a concurrently-firing scheduled task can both call + // this for the same PendingDisconnect. tryClaim() ensures notifyEdgeConnectivity fires at most once without + // relying on downstream notification dedup. + if (!pending.tryClaim()) { + return; + } + Edge edge = pending.getEdge(); EdgeId edgeId = edge.getId(); // Identity-keyed remove: don't clobber a newer entry if a second disconnect races with this task firing. pendingDisconnectNotifications.remove(edgeId, pending); @@ -760,23 +768,25 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cancelPendingDisconnectNotification(EdgeId edgeId) { PendingDisconnect pending = pendingDisconnectNotifications.remove(edgeId); if (pending != null) { - cancelIfPending(pending.future()); + cancelIfPending(pending.getFuture()); } } static final class PendingDisconnect { + private final Edge edge; + private final AtomicBoolean notified = new AtomicBoolean(false); private ScheduledFuture future; PendingDisconnect(Edge edge) { this.edge = edge; } - Edge edge() { + Edge getEdge() { return edge; } - ScheduledFuture future() { + ScheduledFuture getFuture() { return future; } @@ -784,6 +794,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i this.future = future; } + boolean tryClaim() { + return notified.compareAndSet(false, true); + } + } private static void cancelIfPending(ScheduledFuture future) { diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java index 66023c7372..4482177750 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EdgeConnectionNotificationTest.java @@ -30,6 +30,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; import org.thingsboard.server.service.edge.rpc.EdgeGrpcService; +import java.util.Map; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; @@ -101,8 +102,12 @@ public class EdgeConnectionNotificationTest extends AbstractEdgeTest { // Edge drops... edgeImitator.disconnect(); - // Ensure the server processed the disconnect (and scheduled the delayed notification) before reconnecting. - TimeUnit.SECONDS.sleep(1); + // Wait until the server has processed the disconnect and scheduled the pending notification + // (the edge id appears in the pendingDisconnectNotifications map) before reconnecting. + await().atMost(AbstractWebTest.TIMEOUT, TimeUnit.SECONDS).until(() -> { + Map pending = (Map) ReflectionTestUtils.getField(edgeGrpcService, "pendingDisconnectNotifications"); + return pending != null && pending.containsKey(edge.getId()); + }); // ...and reconnects within the delay window, which must cancel the pending "disconnected" notification. EdgeImitator reconnected = createEdgeImitator(); From 31bc775035d738b1cbfa1a3f988787a741e459e4 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 7 Jul 2026 14:58:23 +0300 Subject: [PATCH 007/213] Skip subscription forwarding when tenant no longer exists A device-state attribute save can complete after its tenant was deleted. The post-save WS-update callback then resolves an evicted tenant profile via partitionService.resolve -> getRoutingInfo and throws TenantNotFoundException uncaught on the ws-callback thread. Guard resolve() in forwardToSubscriptionManagerService: a deleted tenant has no partition to route to and no subscribers to notify, so skip the forward instead of propagating. Mirrors the existing tenant-gone handling in DefaultDeviceStateService.checkStates(). --- .../AbstractSubscriptionService.java | 11 +++++++++- ...faultTelemetrySubscriptionServiceTest.java | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/telemetry/AbstractSubscriptionService.java b/application/src/main/java/org/thingsboard/server/service/telemetry/AbstractSubscriptionService.java index 5df3e638f5..7b5a2a0fad 100644 --- a/application/src/main/java/org/thingsboard/server/service/telemetry/AbstractSubscriptionService.java +++ b/application/src/main/java/org/thingsboard/server/service/telemetry/AbstractSubscriptionService.java @@ -25,6 +25,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.exception.TenantNotFoundException; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.msg.queue.ServiceType; @@ -86,7 +87,15 @@ public abstract class AbstractSubscriptionService extends TbApplicationEventList protected void forwardToSubscriptionManagerService(TenantId tenantId, EntityId entityId, Consumer toSubscriptionManagerService, Supplier toCore) { - TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId); + TopicPartitionInfo tpi; + try { + tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId); + } catch (TenantNotFoundException e) { + // The tenant was deleted (e.g. concurrently with an in-flight asynchronous save callback), + // so there is no partition to route to and no subscribers to notify. Nothing to forward. + log.debug("[{}][{}] Skipping subscription update: tenant no longer exists.", tenantId, entityId); + return; + } if (currentPartitions.contains(tpi)) { if (subscriptionManagerService.isPresent()) { toSubscriptionManagerService.accept(subscriptionManagerService.get()); diff --git a/application/src/test/java/org/thingsboard/server/service/telemetry/DefaultTelemetrySubscriptionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/telemetry/DefaultTelemetrySubscriptionServiceTest.java index dcfe9bd2bd..958a41449f 100644 --- a/application/src/test/java/org/thingsboard/server/service/telemetry/DefaultTelemetrySubscriptionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/telemetry/DefaultTelemetrySubscriptionServiceTest.java @@ -40,6 +40,7 @@ import org.thingsboard.server.common.data.ApiUsageStateValue; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.exception.TenantNotFoundException; import org.thingsboard.server.common.data.id.ApiUsageStateId; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; @@ -89,6 +90,7 @@ import java.util.stream.Stream; import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import static com.google.common.util.concurrent.Futures.immediateFuture; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -1155,6 +1157,26 @@ class DefaultTelemetrySubscriptionServiceTest { then(deviceStateManager).shouldHaveNoInteractions(); } + /* --- Subscription forwarding --- */ + + @Test + void shouldSkipSubscriptionForwardWhenTenantWasDeleted() { + // GIVEN the tenant was deleted concurrently, so partition resolution fails + given(partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId)) + .willThrow(new TenantNotFoundException(tenantId)); + + // WHEN forwarding a subscription update (e.g. from an in-flight async save callback) + // THEN it must not propagate the exception + assertThatNoException().isThrownBy(() -> telemetryService.forwardToSubscriptionManagerService( + tenantId, entityId, + sm -> sm.onAttributesUpdate(tenantId, entityId, AttributeScope.SERVER_SCOPE.name(), List.of(), TbCallback.EMPTY), + () -> null)); + + // AND nothing is forwarded, since there is no partition to route to and no subscribers to notify + then(subscriptionManagerService).shouldHaveNoInteractions(); + then(clusterService).shouldHaveNoInteractions(); + } + // used to emulate versions returned by save APIs private static List listOfNNumbers(int N) { return LongStream.range(0, N).boxed().toList(); From 8538b7cc022feb0029dc8b35c0adeec5aa5a3b8f Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 8 Jul 2026 17:48:12 +0300 Subject: [PATCH 008/213] Fix ENTITY_AGGREGATION CF storing numeric results as strings EntityAggregationCalculatedFieldState.toResult() serialized every metric result via ObjectNode.put(name, JacksonUtil.toString(value)), which produces a JSON *string* node even for numeric aggregation results (SUM/AVG/COUNT/...). When persisted (in particular with transport.json.type_cast_enabled=false, or for non-parsable values) the result lands in ts_kv.str_v, so server-side AVG/SUM aggregation returns no data in widgets/queries while COUNT/MIN/MAX still return. Serialize with JacksonUtil.valueToTree(...) so numeric results are emitted as numeric JSON nodes (-> dbl_v/long_v), mirroring RelatedEntitiesAggregationCalculatedFieldState. Genuine string MIN/MAX results over string telemetry are preserved as string nodes. The instanceof Number guard is retained (it only governs rounding). --- .../single/EntityAggregationCalculatedFieldState.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldState.java b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldState.java index c945868576..f50bc602ce 100644 --- a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldState.java +++ b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldState.java @@ -293,7 +293,7 @@ public class EntityAggregationCalculatedFieldState extends BaseCalculatedFieldSt Object resultValue = argumentEntry.getValue() instanceof Number number ? NumberUtils.roundResult(number.doubleValue(), precision) : argumentEntry.getValue(); - metricsNode.put(metricName, JacksonUtil.toString(resultValue)); + metricsNode.set(metricName, JacksonUtil.valueToTree(resultValue)); } } if (!metricsNode.isEmpty()) { From 80d1631bb3d0194a4fdee7692341e0d2fe111140 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 9 Jul 2026 13:35:31 +0300 Subject: [PATCH 009/213] Add regression tests for ENTITY_AGGREGATION CF numeric serialization Cover the fix that makes EntityAggregationCalculatedFieldState.toResult() emit numeric aggregation results as numeric JSON nodes (dbl_v/long_v) instead of JSON strings (str_v), which had broken server-side AVG/SUM aggregation. - New unit test EntityAggregationCalculatedFieldStateTest: asserts toResult() serializes a numeric result as a numeric node and a genuine string result (lexical MIN/MAX over string telemetry) as a string node. Assertions check the node type (isNumber/isTextual) rather than asText(), since asText() coerces both node kinds identically - which is why the bug went unnoticed. - EntityAggregationCalculatedFieldTest: add a strict-types read helper (useStrictDataTypes=true) and a test asserting the stored SUM/AVG telemetry are numeric JSON nodes end-to-end. Existing asText()-based assertions are left untouched (they read via the non-strict endpoint, which stringifies every value and therefore cannot observe the storage type). --- .../EntityAggregationCalculatedFieldTest.java | 44 +++++ ...tyAggregationCalculatedFieldStateTest.java | 179 ++++++++++++++++++ 2 files changed, 223 insertions(+) create mode 100644 application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java diff --git a/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java b/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java index c23c59d137..a51ac508be 100644 --- a/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java +++ b/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java @@ -154,6 +154,44 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest }); } + @Test + public void testAggregationResult_isStoredAsNumericTelemetry() throws Exception { + // Regression: ENTITY_AGGREGATION must store numeric results as numbers (ts_kv.dbl_v/long_v), + // not as JSON strings (ts_kv.str_v) - otherwise server-side AVG/SUM return no data. + // The existing .asText()-based tests cannot catch this (asText coerces both types), so this + // test reads with useStrictDataTypes=true and asserts the value node type. + Device device = createDevice("Device", "1234567890111"); + + CustomInterval customInterval = new CustomInterval(TZ, 0L, 5L); + createConsumptionCF(device.getId(), customInterval, null); + + long currentIntervalStartTs = customInterval.getCurrentIntervalStartTs(); + long tsInInterval_1 = currentIntervalStartTs + 1000; + long tsInInterval_2 = currentIntervalStartTs + 500; + long tsInInterval_3 = currentIntervalStartTs + 200; + postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":100}}", tsInInterval_1)); + postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":180}}", tsInInterval_2)); + postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":120}}", tsInInterval_3)); + + long interval = customInterval.getCurrentIntervalDurationMillis(); + + await().alias("create CF -> aggregation result stored as numeric telemetry") + .atMost(2 * interval, TimeUnit.MILLISECONDS) + .pollInterval(POLL_INTERVAL, TimeUnit.SECONDS) + .untilAsserted(() -> { + ObjectNode result = getLatestTelemetryStrict(device.getId(), "consumption", "avgConsumption"); + assertThat(result).isNotNull(); + assertThat(result.get("consumption")).isNotNull(); + assertThat(result.get("avgConsumption")).isNotNull(); + // SUM and AVG results must be numeric JSON nodes, not strings. + assertThat(result.get("consumption").get(0).get("value").isNumber()).isTrue(); + assertThat(result.get("avgConsumption").get(0).get("value").isNumber()).isTrue(); + // Values are still correct (SUM=400, AVG=133). + assertThat(result.get("consumption").get(0).get("value").asInt()).isEqualTo(400); + assertThat(result.get("avgConsumption").get(0).get("value").asInt()).isEqualTo(133); + }); + } + @Test public void testCreateCfWithWatermark_checkAggregationDuringWatermark() throws Exception { Device device = createDevice("Device", "1234567890111"); @@ -376,4 +414,10 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest return doGetAsync("/api/plugins/telemetry/" + entityId.getEntityType() + "/" + entityId.getId() + "/values/timeseries?keys=" + String.join(",", keys), ObjectNode.class); } + // useStrictDataTypes=true so the value node keeps its stored type (numeric -> JSON number, str_v -> JSON string). + // Without it the endpoint returns every value via getValueAsString(), masking the string-vs-number distinction. + private ObjectNode getLatestTelemetryStrict(EntityId entityId, String... keys) throws Exception { + return doGetAsync("/api/plugins/telemetry/" + entityId.getEntityType() + "/" + entityId.getId() + "/values/timeseries?useStrictDataTypes=true&keys=" + String.join(",", keys), ObjectNode.class); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java new file mode 100644 index 0000000000..22bfcbe276 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java @@ -0,0 +1,179 @@ +/** + * 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.service.cf.ctx.state.aggregation.single; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.actors.ActorSystemContext; +import org.thingsboard.server.common.data.TenantProfile; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.Argument; +import org.thingsboard.server.common.data.cf.configuration.ArgumentType; +import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; +import org.thingsboard.server.common.data.cf.configuration.aggregation.AggFunction; +import org.thingsboard.server.common.data.cf.configuration.aggregation.AggKeyInput; +import org.thingsboard.server.common.data.cf.configuration.aggregation.AggMetric; +import org.thingsboard.server.common.data.cf.configuration.aggregation.single.EntityAggregationCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.aggregation.single.interval.CustomInterval; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.kv.BasicKvEntry; +import org.thingsboard.server.common.data.kv.DoubleDataEntry; +import org.thingsboard.server.common.data.kv.StringDataEntry; +import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; +import org.thingsboard.server.dao.tenant.TbTenantProfileCache; +import org.thingsboard.server.service.cf.ctx.state.ArgumentEntry; +import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx; +import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class EntityAggregationCalculatedFieldStateTest { + + private static final long INTERVAL_START_TS = 1_000L; + private static final long INTERVAL_END_TS = 2_000L; + + private final TenantId TENANT_ID = TenantId.fromUUID(UUID.fromString("80ee80ef-019f-46b1-80ba-22f3ef1b094c")); + private final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("fc83d188-9cf5-4919-a774-d5c56bba2d27")); + + private EntityAggregationCalculatedFieldState state; + private CalculatedFieldCtx ctx; + + @Mock + private TenantProfile tenantProfile; + @Mock + private TbTenantProfileCache tenantProfileCache; + @InjectMocks + private ActorSystemContext systemContext; + + @BeforeEach + void setUp() { + when(tenantProfileCache.get(any(TenantId.class))).thenReturn(tenantProfile); + when(tenantProfile.getProfileConfiguration()).thenReturn(Optional.of(new DefaultTenantProfileConfiguration())); + + ctx = new CalculatedFieldCtx(getCalculatedField(), systemContext); + ctx.init(); + state = new EntityAggregationCalculatedFieldState(DEVICE_ID); + state.setCtx(ctx, null); + state.init(false); + } + + @Test + void testType() { + assertThat(state.getType()).isEqualTo(CalculatedFieldType.ENTITY_AGGREGATION); + } + + // A numeric aggregation result (SUM/AVG/COUNT/..., numeric MIN/MAX) must be serialized as a numeric + // JSON node; a genuine string result (lexical MIN/MAX over string telemetry, spec §7) must stay a string + // node. The node type is asserted explicitly, so asText() is only used to verify the value once the type + // is already pinned - it is not relied on to distinguish the types (that blindness is what hid the bug). + @ParameterizedTest(name = "{0} (precision {2}) -> numeric={3}") + @MethodSource("toResultSerializationCases") + void toResultSerializesResultWithTypePreservingNode(String metricName, BasicKvEntry kvEntry, Integer precision, + boolean expectNumeric, String expectedText) { + JsonNode value = toResultValue(metricName, kvEntry, precision); + + assertThat(value.isNumber()).isEqualTo(expectNumeric); + assertThat(value.isTextual()).isEqualTo(!expectNumeric); + assertThat(value.asText()).isEqualTo(expectedText); + } + + private static Stream toResultSerializationCases() { + return Stream.of( + // SUM: Number result, precision 0 -> whole-number (long) node + arguments("consumption", new DoubleDataEntry("consumption", 400.0), 0, true, "400"), + // AVG: Number result, precision 2 -> half-up rounded double node + arguments("avgConsumption", new DoubleDataEntry("avgConsumption", 133.335), 2, true, "133.34"), + // MIN/MAX over string telemetry: lexical String result -> preserved as string node (spec §7) + arguments("maxCode", new StringDataEntry("maxCode", "9"), 0, false, "9") + ); + } + + private JsonNode toResultValue(String metricName, BasicKvEntry kvEntry, Integer precision) { + AggIntervalEntry interval = new AggIntervalEntry(INTERVAL_START_TS, INTERVAL_END_TS); + ArgumentEntry argumentEntry = new SingleValueArgumentEntry(INTERVAL_START_TS, kvEntry, SingleValueArgumentEntry.DEFAULT_VERSION); + Map> results = new HashMap<>(); + results.put(interval, Map.of(metricName, argumentEntry)); + + ArrayNode result = state.toResult(results, precision); + + assertThat(result.size()).isEqualTo(1); + assertThat(result.get(0).get("ts").asLong()).isEqualTo(INTERVAL_START_TS); + return result.get(0).get("values").get(metricName); + } + + private CalculatedField getCalculatedField() { + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setTenantId(TENANT_ID); + calculatedField.setEntityId(DEVICE_ID); + calculatedField.setType(CalculatedFieldType.ENTITY_AGGREGATION); + calculatedField.setName("Test Entity Aggregation CF"); + calculatedField.setConfigurationVersion(1); + calculatedField.setConfiguration(getConfiguration()); + calculatedField.setVersion(1L); + return calculatedField; + } + + private EntityAggregationCalculatedFieldConfiguration getConfiguration() { + EntityAggregationCalculatedFieldConfiguration configuration = new EntityAggregationCalculatedFieldConfiguration(); + + Argument energy = new Argument(); + energy.setRefEntityKey(new ReferencedEntityKey("energy", ArgumentType.TS_LATEST, null)); + configuration.setArguments(Map.of("en", energy)); + + Map metrics = new HashMap<>(); + AggMetric consumption = new AggMetric(); + consumption.setFunction(AggFunction.SUM); + consumption.setInput(new AggKeyInput("en")); + metrics.put("consumption", consumption); + + AggMetric avgConsumption = new AggMetric(); + avgConsumption.setFunction(AggFunction.AVG); + avgConsumption.setInput(new AggKeyInput("en")); + metrics.put("avgConsumption", avgConsumption); + configuration.setMetrics(metrics); + + configuration.setInterval(new CustomInterval("UTC", 0L, 5L)); + + TimeSeriesOutput output = new TimeSeriesOutput(); + output.setDecimalsByDefault(0); + configuration.setOutput(output); + + return configuration; + } + +} From bf6f0f1ec5e6e0c38b0e9ac05a6faebb4a540ac1 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 9 Jul 2026 14:53:42 +0300 Subject: [PATCH 010/213] Refine ENTITY_AGGREGATION CF numeric regression coverage in integration test Address review feedback on the integration test: - Read latest telemetry with useStrictDataTypes=true always, so the value node keeps its stored type (numeric -> JSON number, str_v -> JSON string). - Assert the aggregation result is a numeric node across all existing scenarios via a shared assertNumericValue helper, instead of a separate standalone test. isNumber() is the actual regression guard; asLong()/asText() would coerce a str_v string and miss it, so the type is asserted explicitly and the value is compared numerically. - Drop the redundant standalone test that duplicated an existing scenario. --- .../EntityAggregationCalculatedFieldTest.java | 85 ++++++------------- 1 file changed, 27 insertions(+), 58 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java b/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java index a51ac508be..71b89bff40 100644 --- a/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java +++ b/application/src/test/java/org/thingsboard/server/cf/EntityAggregationCalculatedFieldTest.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.cf; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.After; import org.junit.Before; @@ -106,7 +107,7 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("9999"); + assertNumericValue(result, "consumption", 9999); assertThat(result.get("avgConsumption").get(0).get("value").isNull()).isTrue(); }); } @@ -137,8 +138,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("400"); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("133"); + assertNumericValue(result, "consumption", 400); + assertNumericValue(result, "avgConsumption", 133); }); postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":500}}", tsInInterval_1)); @@ -149,46 +150,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("400"); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("133"); - }); - } - - @Test - public void testAggregationResult_isStoredAsNumericTelemetry() throws Exception { - // Regression: ENTITY_AGGREGATION must store numeric results as numbers (ts_kv.dbl_v/long_v), - // not as JSON strings (ts_kv.str_v) - otherwise server-side AVG/SUM return no data. - // The existing .asText()-based tests cannot catch this (asText coerces both types), so this - // test reads with useStrictDataTypes=true and asserts the value node type. - Device device = createDevice("Device", "1234567890111"); - - CustomInterval customInterval = new CustomInterval(TZ, 0L, 5L); - createConsumptionCF(device.getId(), customInterval, null); - - long currentIntervalStartTs = customInterval.getCurrentIntervalStartTs(); - long tsInInterval_1 = currentIntervalStartTs + 1000; - long tsInInterval_2 = currentIntervalStartTs + 500; - long tsInInterval_3 = currentIntervalStartTs + 200; - postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":100}}", tsInInterval_1)); - postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":180}}", tsInInterval_2)); - postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":120}}", tsInInterval_3)); - - long interval = customInterval.getCurrentIntervalDurationMillis(); - - await().alias("create CF -> aggregation result stored as numeric telemetry") - .atMost(2 * interval, TimeUnit.MILLISECONDS) - .pollInterval(POLL_INTERVAL, TimeUnit.SECONDS) - .untilAsserted(() -> { - ObjectNode result = getLatestTelemetryStrict(device.getId(), "consumption", "avgConsumption"); - assertThat(result).isNotNull(); - assertThat(result.get("consumption")).isNotNull(); - assertThat(result.get("avgConsumption")).isNotNull(); - // SUM and AVG results must be numeric JSON nodes, not strings. - assertThat(result.get("consumption").get(0).get("value").isNumber()).isTrue(); - assertThat(result.get("avgConsumption").get(0).get("value").isNumber()).isTrue(); - // Values are still correct (SUM=400, AVG=133). - assertThat(result.get("consumption").get(0).get("value").asInt()).isEqualTo(400); - assertThat(result.get("avgConsumption").get(0).get("value").asInt()).isEqualTo(133); + assertNumericValue(result, "consumption", 400); + assertNumericValue(result, "avgConsumption", 133); }); } @@ -219,8 +182,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("400"); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("133"); + assertNumericValue(result, "consumption", 400); + assertNumericValue(result, "avgConsumption", 133); }); postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":300}}", tsInInterval_1)); @@ -231,8 +194,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("600"); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("200"); + assertNumericValue(result, "consumption", 600); + assertNumericValue(result, "avgConsumption", 200); }); } @@ -269,8 +232,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("400"); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("133"); + assertNumericValue(result, "consumption", 400); + assertNumericValue(result, "avgConsumption", 133); }); postTelemetry(device.getId(), String.format("{\"ts\": \"%s\", \"values\": {\"energy\":500}}", currentIntervalStartTs + 4500L)); @@ -281,9 +244,9 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgConsumption"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("500"); + assertNumericValue(result, "consumption", 500); assertThat(result.get("consumption").get(0).get("ts").asLong()).isEqualTo(currentIntervalStartTs + 4000L); - assertThat(result.get("avgConsumption").get(0).get("value").asText()).isEqualTo("500"); + assertNumericValue(result, "avgConsumption", 500); assertThat(result.get("avgConsumption").get(0).get("ts").asLong()).isEqualTo(currentIntervalStartTs + 4000L); }); } @@ -344,8 +307,8 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest .untilAsserted(() -> { ObjectNode result = getLatestTelemetry(device.getId(), "consumption", "avgTemperature"); assertThat(result).isNotNull(); - assertThat(result.get("consumption").get(0).get("value").asText()).isEqualTo("400"); - assertThat(result.get("avgTemperature").get(0).get("value").asText()).isEqualTo("39"); + assertNumericValue(result, "consumption", 400); + assertNumericValue(result, "avgTemperature", 39); }); } @@ -410,14 +373,20 @@ public class EntityAggregationCalculatedFieldTest extends AbstractControllerTest return saveCalculatedField(calculatedField); } - private ObjectNode getLatestTelemetry(EntityId entityId, String... keys) throws Exception { - return doGetAsync("/api/plugins/telemetry/" + entityId.getEntityType() + "/" + entityId.getId() + "/values/timeseries?keys=" + String.join(",", keys), ObjectNode.class); - } - // useStrictDataTypes=true so the value node keeps its stored type (numeric -> JSON number, str_v -> JSON string). // Without it the endpoint returns every value via getValueAsString(), masking the string-vs-number distinction. - private ObjectNode getLatestTelemetryStrict(EntityId entityId, String... keys) throws Exception { + private ObjectNode getLatestTelemetry(EntityId entityId, String... keys) throws Exception { return doGetAsync("/api/plugins/telemetry/" + entityId.getEntityType() + "/" + entityId.getId() + "/values/timeseries?useStrictDataTypes=true&keys=" + String.join(",", keys), ObjectNode.class); } + // Regression guard: a numeric aggregation result must be stored as a numeric JSON node (ts_kv.dbl_v/long_v), + // not a JSON string (ts_kv.str_v) - otherwise server-side AVG/SUM return no data. A value-only check would + // not catch this: asLong()/asText() coerce a string node like "400" to the same value/text, so the node type + // is asserted explicitly; the numeric comparison then verifies the aggregated value. + private static void assertNumericValue(ObjectNode result, String key, long expectedValue) { + JsonNode value = result.get(key).get(0).get("value"); + assertThat(value.isNumber()).as(key + " should be stored as a numeric node").isTrue(); + assertThat(value.asLong()).isEqualTo(expectedValue); + } + } From da3f2e933a81af2551746134228b41724ca70b36 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 9 Jul 2026 15:53:36 +0300 Subject: [PATCH 011/213] Address review comments on EntityAggregationCalculatedFieldStateTest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Drop the dangling "spec §7" reference from the test comments; inline the actual rule (a lexical MIN/MAX result over string telemetry stays a string). - Use a zero-padded code ("0009") for the string-result case - a clearer example of a genuine string that must not be coerced to a number (would lose padding). - Define the maxCode metric in the test CF configuration alongside consumption and avgConsumption, so all parameterized metric names are configured. --- ...tityAggregationCalculatedFieldStateTest.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java index 22bfcbe276..8f7cda872e 100644 --- a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java +++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/aggregation/single/EntityAggregationCalculatedFieldStateTest.java @@ -98,9 +98,10 @@ public class EntityAggregationCalculatedFieldStateTest { } // A numeric aggregation result (SUM/AVG/COUNT/..., numeric MIN/MAX) must be serialized as a numeric - // JSON node; a genuine string result (lexical MIN/MAX over string telemetry, spec §7) must stay a string - // node. The node type is asserted explicitly, so asText() is only used to verify the value once the type - // is already pinned - it is not relied on to distinguish the types (that blindness is what hid the bug). + // JSON node; a genuine string result (lexical MIN/MAX over string telemetry, e.g. a zero-padded code) + // must stay a string node. The node type is asserted explicitly, so asText() is only used to verify the + // value once the type is already pinned - it is not relied on to distinguish the types (that blindness + // is what hid the bug). @ParameterizedTest(name = "{0} (precision {2}) -> numeric={3}") @MethodSource("toResultSerializationCases") void toResultSerializesResultWithTypePreservingNode(String metricName, BasicKvEntry kvEntry, Integer precision, @@ -118,8 +119,9 @@ public class EntityAggregationCalculatedFieldStateTest { arguments("consumption", new DoubleDataEntry("consumption", 400.0), 0, true, "400"), // AVG: Number result, precision 2 -> half-up rounded double node arguments("avgConsumption", new DoubleDataEntry("avgConsumption", 133.335), 2, true, "133.34"), - // MIN/MAX over string telemetry: lexical String result -> preserved as string node (spec §7) - arguments("maxCode", new StringDataEntry("maxCode", "9"), 0, false, "9") + // MAX over string telemetry: a zero-padded code is a genuine String result and must stay a + // string node - as a number it would lose its padding ("0009" -> 9). + arguments("maxCode", new StringDataEntry("maxCode", "0009"), 0, false, "0009") ); } @@ -165,6 +167,11 @@ public class EntityAggregationCalculatedFieldStateTest { avgConsumption.setFunction(AggFunction.AVG); avgConsumption.setInput(new AggKeyInput("en")); metrics.put("avgConsumption", avgConsumption); + + AggMetric maxCode = new AggMetric(); + maxCode.setFunction(AggFunction.MAX); + maxCode.setInput(new AggKeyInput("en")); + metrics.put("maxCode", maxCode); configuration.setMetrics(metrics); configuration.setInterval(new CustomInterval("UTC", 0L, 5L)); From 1b9b30e49c9485e2923dae5d94648d435d8599d2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 13 Jul 2026 16:04:37 +0300 Subject: [PATCH 012/213] Move LTS version range check into LtsVersion --- .../server/service/install/lts/LtsMigrationService.java | 4 +--- .../server/service/install/lts/LtsVersion.java | 8 ++++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java index ccafa88234..580db32666 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java @@ -126,9 +126,7 @@ public class LtsMigrationService { // so a cross-family upgrade is fully handled by the target-family migrations. // Excluding the dormant older-family beans avoids double-processing. static boolean isInRangeForTargetFamily(LtsVersion version, LtsVersion from, LtsVersion to) { - return version.sameFamily(to) - && version.compareTo(from) > 0 - && version.compareTo(to) <= 0; + return version.sameFamily(to) && version.isInRange(from, to); } private void runSchemaUpdate(String version) { diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java index cb55e61b3e..9a0fa5be34 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsVersion.java @@ -37,6 +37,14 @@ public record LtsVersion(int major, int minor, int maintenance, int patch) imple return major == other.major && minor == other.minor; } + /** + * Half-open range check: {@code from < this <= to}. The lower bound is exclusive (a source already at + * {@code from} has applied that version) and the upper bound inclusive (the target version's own migration runs). + */ + public boolean isInRange(LtsVersion from, LtsVersion to) { + return compareTo(from) > 0 && compareTo(to) <= 0; + } + @Override public int compareTo(LtsVersion o) { int c = Integer.compare(major, o.major); From 4448c3c646e9597f0fe7f160cc5d90d7c753a645 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Tue, 21 Jul 2026 11:20:07 +0200 Subject: [PATCH 013/213] Updated functionality block at System Administrator level --- ui-ngx/src/assets/dashboard/sys_admin_home_page.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json b/ui-ngx/src/assets/dashboard/sys_admin_home_page.json index 739402e72f..860afa84c8 100644 --- a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json +++ b/ui-ngx/src/assets/dashboard/sys_admin_home_page.json @@ -194,7 +194,8 @@ "padding": "16px", "settings": { "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
\n
widgets.functions.title
\n
\n {{ 'widgets.functions.switch-to-pe' | translate }}\n
\n
\n
\n
widgets.functions.alarms
\n
widgets.functions.dashboards
\n
widgets.functions.entities-and-relations
\n
widgets.functions.profiles
\n
widgets.functions.advanced-features
\n
\n
\n
widgets.functions.notification-center
\n
widgets.functions.api-usage
\n
widgets.functions.customers
\n
widgets.functions.customers-hierarchy
\n
widgets.functions.roles-and-permissions
\n
\n
\n
widgets.functions.groups
\n
widgets.functions.integrations
\n
widgets.functions.solution-templates
\n
widgets.functions.scheduler
\n
widgets.functions.white-labeling
\n
\n
\n
", + "markdownTextPattern": "
\n
\n
\n
widgets.functions.title
\n
\n {{ 'widgets.functions.switch-to-pe' | translate }}\n
\n
\n
\n
widgets.functions.alarms
\n
widgets.functions.dashboards
\n
widgets.functions.entities-and-relations
\n
widgets.functions.profiles
\n
widgets.functions.advanced-features
\n
widgets.functions.solution-templates
\n
\n
\n
widgets.functions.notification-center
\n
widgets.functions.api-usage
\n
widgets.functions.customers
\n
widgets.functions.customers-hierarchy
\n
widgets.functions.roles-and-permissions
\n
\n
\n
widgets.functions.groups
\n
widgets.functions.integrations
\n
widgets.functions.scheduler
\n
widgets.functions.white-labeling
\n
\n
\n
", + "markdownTextFunction": "return '# Some title\\\\n - Entity name: ' + data[0]['entityName'];", "applyDefaultMarkdownStyle": false, "markdownCss": ".tb-card-header {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n}\n\n.tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n margin-top: 4px;\n overflow: auto;\n}\n\n.tb-card-column {\n min-width: 0px;\n flex: 1;\n display: flex;\n flex-direction: column;\n}\n\n.feature {\n position: relative;\n cursor: default;\n font-weight: 400;\n font-size: 14px;\n line-height: 28px;\n letter-spacing: 0.2px;\n color: rgba(0, 0, 0, 0.76);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.feature:before {\n content: \"check\";\n font-family: 'Material Icons Round';\n display: inline-block;\n font-size: 20px;\n line-height: 20px;\n color: #198038;\n font-weight: 600;\n position: relative;\n background: #F3F6FA;\n border-radius: 4px;\n width: 20px;\n height: 20px;\n padding: 2px;\n vertical-align: sub;\n margin-right: 8px;\n}\n\n.feature.pe:before {\n content: \"close\";\n background: #F4F4F4;\n color: rgba(0, 0, 0, 0.12);\n}\n\n.feature.pe:after {\n position: relative;\n display: inline-block;\n margin-left: 4px;\n vertical-align: baseline;\n top: -0.5em;\n content: \"PE\";\n color: #305680;\n font-weight: 700;\n font-size: 12px;\n line-height: 12px;\n letter-spacing: 0.0015em;\n}\n\n.feature+.feature {\n margin-top: 4px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-switch-to-pe {\n height: 24px;\n font-size: 12px;\n padding: 0 4px;\n }\n \n .feature+.feature {\n margin-top: 2px;\n }\n \n .feature {\n font-size: 11px;\n line-height: 18px;\n }\n\n .feature:before {\n font-size: 14px;\n line-height: 14px;\n width: 14px;\n height: 14px;\n margin-right: 4px;\n }\n .feature.pe:after {\n margin-left: 2px;\n top: -0.5em;\n content: \"PE\";\n font-size: 8px;\n line-height: 8px;\n }\n \n}\n\n" }, From 43851cd3f0236ebf9603ee6f2b297b59c471e98f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:27 +0300 Subject: [PATCH 014/213] Fix Nashorn Global PropertyMap leak on JS script release --- .../script/NashornJsInvokeServiceTest.java | 85 +++++++++++++++++++ .../script/api/js/NashornJsInvokeService.java | 16 +++- 2 files changed, 97 insertions(+), 4 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index 01a5f1b6fc..c76eac8c61 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -17,13 +17,17 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import delight.nashornsandbox.NashornSandbox; +import delight.nashornsandbox.NashornSandboxes; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.TbStopWatch; +import org.thingsboard.script.api.RuleNodeScriptFactory; import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.TbScriptException; import org.thingsboard.script.api.js.NashornJsInvokeService; @@ -31,6 +35,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; @@ -222,6 +227,86 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { }); } + @Test + void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { + UUID scriptId = evalScript("return msg;"); + String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("true"); + + invokeService.release(scriptId).get(); + + // the property must be deleted, not just set to undefined: an abandoned binding keeps + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("false"); + } + + @Test + void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception { + UUID scriptId = evalScript("return {doubled: msg.temperature * 2};"); + assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42"); + } + + @Test + void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception { + UUID writer = evalScript("compatSharedState = 777; return msg;"); + UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};"); + invokeScript(writer, "{}"); + assertThat(invokeScript(reader, "{}")).contains("\"seen\":777"); + } + + @Test + void givenIifeWrappedEval_thenCompilationErrorUnchanged() { + String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;"; + + String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript, + "msg", "metadata", "msgType"); + NashornSandbox legacySandbox = NashornSandboxes.create(); + legacySandbox.allowNoBraces(false); + legacySandbox.allowLoadFunctions(true); + legacySandbox.setMaxPreparedStatements(30); + int legacyErrorLine = -1; + try { + legacySandbox.eval(legacyScript); + } catch (ScriptException e) { + legacyErrorLine = e.getLineNumber(); + } + assertThat(legacyErrorLine).isGreaterThan(0); + final int expectedLine = legacyErrorLine; + + assertThatThrownBy(() -> evalScript(badScript)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION); + assertThat(ex.getBody()).contains(badScript); + assertThat(ex.getCause()).isInstanceOf(ScriptException.class); + // The IIFE wrapper shifts sandbox-reported line numbers by a constant +2 + // (the beautifier splits the wrapper prefix onto its own lines). Reported + // lines never matched the user's source anyway (the sandbox instrumentation + // already offsets them), so only the small constant shift is tolerated here. + assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2); + }); + } + + @Test + void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception { + UUID scriptId = evalScript("return msg;"); + invokeScript(scriptId, "{}"); + invokeService.release(scriptId).get(); + assertThatThrownBy(() -> invokeScript(scriptId, "{}")) + .isInstanceOf(ExecutionException.class) + .hasMessageContaining("No compiled script found"); + } + + private Object evalInEngine(String expression) throws Exception { + Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox"); + if (sandbox != null) { + return ((NashornSandbox) sandbox).eval(expression); + } + return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScript(scriptId, "{}"); diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index 1ef2eeb6da..bb95c60481 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -140,14 +140,21 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { @Override protected ListenableFuture doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) { + // A top-level function declaration creates a non-configurable property on the Nashorn Global + // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap + // shape history forever. Declaring the function inside an IIFE and assigning it to a global + // property keeps the property configurable, allowing doRelease() to actually delete it. + // The prefix stays on the first line so that script line numbers in errors are unchanged. + String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { try { evalLock.lock(); try { if (useJsSandbox) { - sandbox.eval(jsScript); + sandbox.eval(wrappedScript); } else { - engine.eval(jsScript); + engine.eval(wrappedScript); } } finally { evalLock.unlock(); @@ -182,10 +189,11 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { } protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { + String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; if (useJsSandbox) { - sandbox.eval(scriptInfo.getFunctionName() + " = undefined;"); + sandbox.eval(deleteScript); } else { - engine.eval(scriptInfo.getFunctionName() + " = undefined;"); + engine.eval(deleteScript); } } From b67fc8dfb1ad1ca22dc076047f8ee37743b894f2 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:39 +0300 Subject: [PATCH 015/213] Release EdgeGrpcClient channel on failed connect and guard send/disconnect race --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 146 +++++++++++------- 1 file changed, 92 insertions(+), 54 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index 7e58a2cb9f..f96fe8b38f 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -86,7 +86,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private StreamObserver inputStream; - private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); + private final ReentrantLock connectionLock = new ReentrantLock(); @Override public void connect(String edgeKey, @@ -127,19 +127,38 @@ public class EdgeGrpcClient implements EdgeRpcClient { .build()); } - channel = builder.build(); - EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); - log.info("[{}] Sending a connect request to the TB!", edgeKey); - this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) - .setConnectRequestMsg(ConnectRequestMsg.newBuilder() - .setEdgeRoutingKey(edgeKey) - .setEdgeSecret(edgeSecret) - .setEdgeVersion(getNewestEdgeVersion()) - .setMaxInboundMessageSize(maxInboundMessageSize) - .build()) - .build()); + connectionLock.lock(); + try { + channel = builder.build(); + EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); + log.info("[{}] Sending a connect request to the TB!", edgeKey); + this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, channel, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) + .setConnectRequestMsg(ConnectRequestMsg.newBuilder() + .setEdgeRoutingKey(edgeKey) + .setEdgeSecret(edgeSecret) + .setEdgeVersion(getNewestEdgeVersion()) + .setMaxInboundMessageSize(maxInboundMessageSize) + .build()) + .build()); + } catch (RuntimeException e) { + // Release the half-built channel, otherwise every failed reconnect attempt leaks + // its event loops and executors, and the next attempt may not recover at all. + log.error("[{}] Failed to establish the connection, shutting down the channel!", edgeKey, e); + if (channel != null) { + try { + channel.shutdownNow(); + } catch (Exception shutdownEx) { + log.error("[{}] Exception during shutdownNow of the failed channel", edgeKey, shutdownEx); + } + } + channel = null; + inputStream = null; + throw e; + } finally { + connectionLock.unlock(); + } } public static EdgeVersion getNewestEdgeVersion() { @@ -147,6 +166,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } private StreamObserver initOutputStream(String edgeKey, + ManagedChannel streamChannel, Consumer onUplinkResponse, Consumer onEdgeUpdate, Consumer onDownlink, @@ -166,7 +186,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -188,7 +208,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void onError(Throwable t) { log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -204,77 +224,95 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { - if (!onError) { - try { - if (inputStream != null) { - inputStream.onCompleted(); + disconnect(onError, null); + } + + private void disconnect(boolean onError, ManagedChannel expectedChannel) throws InterruptedException { + ManagedChannel channelToShutdown; + connectionLock.lock(); + try { + // A terminated stream reports its error asynchronously and may lose the race with a + // reconnect: ignore such stale callbacks instead of tearing down the fresh channel. + if (expectedChannel != null && channel != expectedChannel) { + log.info("The channel was already replaced by a reconnect. Skipping disconnect of the stale channel."); + return; + } + if (!onError) { + try { + if (inputStream != null) { + inputStream.onCompleted(); + } + } catch (Exception e) { + log.error("Exception during onCompleted", e); } - } catch (Exception e) { - log.error("Exception during onCompleted", e); } + // Clear the references under the lock so that no send can start against a stream + // whose channel is shutting down - such a write leaks the compressed ByteBuf. + inputStream = null; + channelToShutdown = channel; + channel = null; + } finally { + connectionLock.unlock(); } - if (channel != null) { - channel.shutdown(); + if (channelToShutdown != null) { + channelToShutdown.shutdown(); int attempt = 0; do { try { - channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); + channelToShutdown.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { - channel.shutdownNow(); + channelToShutdown.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; - } while (!channel.isTerminated()); + } while (!channelToShutdown.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { - uplinkMsgLock.lock(); - try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setUplinkMsg(msg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(msg) + .build()); } @Override public void sendSyncRequestMsg(boolean fullSyncRequired) { - uplinkMsgLock.lock(); - try { - SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() - .setFullSync(fullSyncRequired) - .build(); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) - .setSyncRequestMsg(syncRequestMsg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() + .setFullSync(fullSyncRequired) + .build(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) + .setSyncRequestMsg(syncRequestMsg) + .build()); } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { - uplinkMsgLock.lock(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setDownlinkResponseMsg(downlinkResponseMsg) + .build()); + } + + private void sendRequestMsg(RequestMsg requestMsg) { + connectionLock.lock(); try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setDownlinkResponseMsg(downlinkResponseMsg) - .build()); + if (inputStream == null) { + throw new IllegalStateException("Edge is not connected to the cloud. The message is discarded!"); + } + inputStream.onNext(requestMsg); } finally { - uplinkMsgLock.unlock(); + connectionLock.unlock(); } } From 7d3959036ba790fb3556009667108e841016c434 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Wed, 29 Jul 2026 13:36:34 +0300 Subject: [PATCH 016/213] sparkplug^ fix_bug close session after connect nodde --- .../mqtt/session/AbstractGatewaySessionHandler.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java b/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java index 8ea6480142..905814d06d 100644 --- a/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java +++ b/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java @@ -845,7 +845,14 @@ public abstract class AbstractGatewaySessionHandler Date: Wed, 29 Jul 2026 14:18:20 +0300 Subject: [PATCH 017/213] sparkplug: fix_bug close session after connect nodde - 2 --- .../transport/mqtt/session/AbstractGatewaySessionHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java b/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java index 905814d06d..6130d49bfc 100644 --- a/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java +++ b/common/transport/mqtt/src/main/java/org/thingsboard/server/transport/mqtt/session/AbstractGatewaySessionHandler.java @@ -846,8 +846,7 @@ public abstract class AbstractGatewaySessionHandler Date: Thu, 30 Jul 2026 16:22:11 +0200 Subject: [PATCH 018/213] Changed sequence --- ui-ngx/src/assets/dashboard/sys_admin_home_page.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json b/ui-ngx/src/assets/dashboard/sys_admin_home_page.json index 860afa84c8..97ef4feb2d 100644 --- a/ui-ngx/src/assets/dashboard/sys_admin_home_page.json +++ b/ui-ngx/src/assets/dashboard/sys_admin_home_page.json @@ -194,7 +194,7 @@ "padding": "16px", "settings": { "useMarkdownTextFunction": false, - "markdownTextPattern": "
\n
\n
\n
widgets.functions.title
\n
\n {{ 'widgets.functions.switch-to-pe' | translate }}\n
\n
\n
\n
widgets.functions.alarms
\n
widgets.functions.dashboards
\n
widgets.functions.entities-and-relations
\n
widgets.functions.profiles
\n
widgets.functions.advanced-features
\n
widgets.functions.solution-templates
\n
\n
\n
widgets.functions.notification-center
\n
widgets.functions.api-usage
\n
widgets.functions.customers
\n
widgets.functions.customers-hierarchy
\n
widgets.functions.roles-and-permissions
\n
\n
\n
widgets.functions.groups
\n
widgets.functions.integrations
\n
widgets.functions.scheduler
\n
widgets.functions.white-labeling
\n
\n
\n
", + "markdownTextPattern": "
\n
\n
\n
widgets.functions.title
\n
\n {{ 'widgets.functions.switch-to-pe' | translate }}\n
\n
\n
\n
widgets.functions.alarms
\n
widgets.functions.dashboards
\n
widgets.functions.entities-and-relations
\n
widgets.functions.profiles
\n
widgets.functions.advanced-features
\n
\n
\n
widgets.functions.notification-center
\n
widgets.functions.api-usage
\n
widgets.functions.customers
\n
widgets.functions.solution-templates
\n
widgets.functions.customers-hierarchy
\n
\n
\n
widgets.functions.roles-and-permissions
\n
widgets.functions.groups
\n
widgets.functions.integrations
\n
widgets.functions.scheduler
\n
widgets.functions.white-labeling
\n
\n
\n
", "markdownTextFunction": "return '# Some title\\\\n - Entity name: ' + data[0]['entityName'];", "applyDefaultMarkdownStyle": false, "markdownCss": ".tb-card-header {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n}\n\n.tb-card-content {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: row;\n margin-top: 4px;\n overflow: auto;\n}\n\n.tb-card-column {\n min-width: 0px;\n flex: 1;\n display: flex;\n flex-direction: column;\n}\n\n.feature {\n position: relative;\n cursor: default;\n font-weight: 400;\n font-size: 14px;\n line-height: 28px;\n letter-spacing: 0.2px;\n color: rgba(0, 0, 0, 0.76);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.feature:before {\n content: \"check\";\n font-family: 'Material Icons Round';\n display: inline-block;\n font-size: 20px;\n line-height: 20px;\n color: #198038;\n font-weight: 600;\n position: relative;\n background: #F3F6FA;\n border-radius: 4px;\n width: 20px;\n height: 20px;\n padding: 2px;\n vertical-align: sub;\n margin-right: 8px;\n}\n\n.feature.pe:before {\n content: \"close\";\n background: #F4F4F4;\n color: rgba(0, 0, 0, 0.12);\n}\n\n.feature.pe:after {\n position: relative;\n display: inline-block;\n margin-left: 4px;\n vertical-align: baseline;\n top: -0.5em;\n content: \"PE\";\n color: #305680;\n font-weight: 700;\n font-size: 12px;\n line-height: 12px;\n letter-spacing: 0.0015em;\n}\n\n.feature+.feature {\n margin-top: 4px;\n}\n\n@media screen and (min-width: 960px) and (max-width: 1819px) {\n .tb-switch-to-pe {\n height: 24px;\n font-size: 12px;\n padding: 0 4px;\n }\n \n .feature+.feature {\n margin-top: 2px;\n }\n \n .feature {\n font-size: 11px;\n line-height: 18px;\n }\n\n .feature:before {\n font-size: 14px;\n line-height: 14px;\n width: 14px;\n height: 14px;\n margin-right: 4px;\n }\n .feature.pe:after {\n margin-left: 2px;\n top: -0.5em;\n content: \"PE\";\n font-size: 8px;\n line-height: 8px;\n }\n \n}\n\n" From 6de4b30e5ff22848cbab5cb26eb951c5c6b685c5 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 4 Aug 2026 16:01:34 +0300 Subject: [PATCH 019/213] Unblock and interrupt edge event consumer on session destroy --- .../server/service/edge/rpc/EdgeGrpcSession.java | 2 +- .../server/service/edge/rpc/KafkaEdgeGrpcSession.java | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index fb420d080a..1e9a0ade87 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -760,7 +760,7 @@ public abstract class EdgeGrpcSession implements Closeable { ctx.getClusterService().onEdgeEventUpdate(new EdgeEventUpdateMsg(edge.getTenantId(), edge.getId())); } - private void stopCurrentSendDownlinkMsgsTask(Boolean isInterrupted) { + protected void stopCurrentSendDownlinkMsgsTask(Boolean isInterrupted) { if (sessionState.getSendDownlinkMsgsFuture() != null && !sessionState.getSendDownlinkMsgsFuture().isDone()) { sessionState.getSendDownlinkMsgsFuture().set(isInterrupted); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/KafkaEdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/KafkaEdgeGrpcSession.java index 67c0a19e66..e1acc08ba3 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/KafkaEdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/KafkaEdgeGrpcSession.java @@ -156,6 +156,7 @@ public class KafkaEdgeGrpcSession extends EdgeGrpcSession { @Override public boolean destroy() { + stopCurrentSendDownlinkMsgsTask(true); try { if (consumer != null) { log.info("[{}][{}] Stopping edge event consumer...", tenantId, edge != null ? edge.getId() : null); @@ -180,9 +181,13 @@ public class KafkaEdgeGrpcSession extends EdgeGrpcSession { private void awaitConsumerTermination() { try { - consumerExecutor.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS); + if (!consumerExecutor.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) { + // without this the thread is leaked for the whole remaining delivery-retry window (or forever, if the future is never completed). + consumerExecutor.shutdownNow(); + } } catch (InterruptedException ie) { log.warn("[{}][{}] Interrupted while awaiting consumer executor termination", tenantId, edge.getId()); + Thread.currentThread().interrupt(); } } From e2617bcd8e15f34e1ed6d1240a2577e5af5f248c Mon Sep 17 00:00:00 2001 From: IrynaMatveieva Date: Wed, 5 Aug 2026 16:06:22 +0300 Subject: [PATCH 020/213] Fix TelemetryObserveStrategy enum values in OpenAPI spec --- .../device/profile/lwm2m/TelemetryObserveStrategy.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/TelemetryObserveStrategy.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/TelemetryObserveStrategy.java index 53dafe19b7..615bd4f32e 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/TelemetryObserveStrategy.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/TelemetryObserveStrategy.java @@ -15,8 +15,13 @@ */ package org.thingsboard.server.common.data.device.profile.lwm2m; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Getter; +@Schema(description = "Observation strategy for telemetry. " + + "SINGLE (0): one resource equals one single observe request. " + + "COMPOSITE_ALL (1): all resources in one composite observe request. " + + "COMPOSITE_BY_OBJECT (2): grouped composite observe requests by object.") public enum TelemetryObserveStrategy { SINGLE("One resource equals one single observe request", 0), @@ -52,8 +57,4 @@ public enum TelemetryObserveStrategy { throw new IllegalArgumentException("Unknown TelemetryObserveStrategy id: " + id); } - @Override - public String toString() { - return name() + " (" + id + "): " + description; - } } From 4d6600834cfc4a4f1cdf159b5634f842faad741a Mon Sep 17 00:00:00 2001 From: IrynaMatveieva Date: Thu, 6 Aug 2026 16:29:06 +0300 Subject: [PATCH 021/213] Add OpenAPI discriminator mapping to polymorphic LwM2M and job types --- .../lwm2m/LwM2MBootstrapClientCredential.java | 11 +++++++++++ .../credentials/lwm2m/LwM2MClientCredential.java | 11 +++++++++++ .../bootstrap/LwM2MBootstrapServerCredential.java | 11 +++++++++++ .../thingsboard/server/common/data/job/task/Task.java | 8 ++++++++ .../server/common/data/job/task/TaskResult.java | 8 ++++++++ 5 files changed, 49 insertions(+) diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MBootstrapClientCredential.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MBootstrapClientCredential.java index 9041de33f0..008c01e7de 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MBootstrapClientCredential.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MBootstrapClientCredential.java @@ -19,7 +19,18 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.v3.oas.annotations.media.DiscriminatorMapping; +import io.swagger.v3.oas.annotations.media.Schema; +@Schema( + discriminatorProperty = "securityMode", + discriminatorMapping = { + @DiscriminatorMapping(value = "NO_SEC", schema = NoSecBootstrapClientCredential.class), + @DiscriminatorMapping(value = "PSK", schema = PSKBootstrapClientCredential.class), + @DiscriminatorMapping(value = "RPK", schema = RPKBootstrapClientCredential.class), + @DiscriminatorMapping(value = "X509", schema = X509BootstrapClientCredential.class) + } +) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "securityMode") diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MClientCredential.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MClientCredential.java index 0ac1911d81..3f939cbd5b 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MClientCredential.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/credentials/lwm2m/LwM2MClientCredential.java @@ -19,7 +19,18 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.v3.oas.annotations.media.DiscriminatorMapping; +import io.swagger.v3.oas.annotations.media.Schema; +@Schema( + discriminatorProperty = "securityConfigClientMode", + discriminatorMapping = { + @DiscriminatorMapping(value = "NO_SEC", schema = NoSecClientCredential.class), + @DiscriminatorMapping(value = "PSK", schema = PSKClientCredential.class), + @DiscriminatorMapping(value = "RPK", schema = RPKClientCredential.class), + @DiscriminatorMapping(value = "X509", schema = X509ClientCredential.class) + } +) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "securityConfigClientMode") diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MBootstrapServerCredential.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MBootstrapServerCredential.java index 71e00cd354..1e6e3d056e 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MBootstrapServerCredential.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MBootstrapServerCredential.java @@ -19,10 +19,21 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.v3.oas.annotations.media.DiscriminatorMapping; +import io.swagger.v3.oas.annotations.media.Schema; import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode; import java.io.Serializable; +@Schema( + discriminatorProperty = "securityMode", + discriminatorMapping = { + @DiscriminatorMapping(value = "NO_SEC", schema = NoSecLwM2MBootstrapServerCredential.class), + @DiscriminatorMapping(value = "PSK", schema = PSKLwM2MBootstrapServerCredential.class), + @DiscriminatorMapping(value = "RPK", schema = RPKLwM2MBootstrapServerCredential.class), + @DiscriminatorMapping(value = "X509", schema = X509LwM2MBootstrapServerCredential.class) + } +) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "securityMode") diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/job/task/Task.java b/common/data/src/main/java/org/thingsboard/server/common/data/job/task/Task.java index a881780012..bf12d50ece 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/job/task/Task.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/job/task/Task.java @@ -20,6 +20,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.v3.oas.annotations.media.DiscriminatorMapping; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.experimental.SuperBuilder; @@ -29,6 +31,12 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.job.JobType; @Data +@Schema( + discriminatorProperty = "jobType", + discriminatorMapping = { + @DiscriminatorMapping(value = "DUMMY", schema = DummyTask.class) + } +) @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "jobType") @JsonSubTypes({ diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/job/task/TaskResult.java b/common/data/src/main/java/org/thingsboard/server/common/data/job/task/TaskResult.java index e882c74eb6..ac55f14b0f 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/job/task/TaskResult.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/job/task/TaskResult.java @@ -20,12 +20,20 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.v3.oas.annotations.media.DiscriminatorMapping; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.NoArgsConstructor; import org.thingsboard.server.common.data.job.JobType; @Data @NoArgsConstructor +@Schema( + discriminatorProperty = "jobType", + discriminatorMapping = { + @DiscriminatorMapping(value = "DUMMY", schema = DummyTaskResult.class) + } +) @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "jobType") @JsonSubTypes({ From 8237be6c2bd0e31ded4d2c663d41fc19225a16e7 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 10 Aug 2026 17:13:57 +0300 Subject: [PATCH 022/213] Fix uplink stall and off-heap memory growth after cloud disconnect --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 57 ++++++ .../thingsboard/edge/rpc/EdgeRpcClient.java | 2 + .../edge/rpc/EdgeGrpcClientLeakTest.java | 168 ++++++++++++++++++ 3 files changed, 227 insertions(+) create mode 100644 common/edge-api/src/test/java/org/thingsboard/edge/rpc/EdgeGrpcClientLeakTest.java diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index 7e58a2cb9f..e78ca440a6 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -19,8 +19,17 @@ import io.grpc.HttpConnectProxiedSocketAddress; import io.grpc.ManagedChannel; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.netty.channel.Channel; +import io.grpc.netty.shaded.io.netty.channel.EventLoopGroup; +import io.grpc.netty.shaded.io.netty.channel.epoll.Epoll; +import io.grpc.netty.shaded.io.netty.channel.epoll.EpollEventLoopGroup; +import io.grpc.netty.shaded.io.netty.channel.epoll.EpollSocketChannel; +import io.grpc.netty.shaded.io.netty.channel.nio.NioEventLoopGroup; +import io.grpc.netty.shaded.io.netty.channel.socket.nio.NioSocketChannel; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.netty.shaded.io.netty.util.concurrent.DefaultThreadFactory; import io.grpc.stub.StreamObserver; +import jakarta.annotation.PreDestroy; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; @@ -84,8 +93,12 @@ public class EdgeGrpcClient implements EdgeRpcClient { private ManagedChannel channel; + private EventLoopGroup workerGroup; + private StreamObserver inputStream; + private volatile boolean connected; + private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); @Override @@ -95,7 +108,13 @@ public class EdgeGrpcClient implements EdgeRpcClient { Consumer onEdgeUpdate, Consumer onDownlink, Consumer onError) { + connected = false; + if (workerGroup == null) { + workerGroup = createWorkerGroup(); + } NettyChannelBuilder builder = NettyChannelBuilder.forAddress(rpcHost, rpcPort) + .eventLoopGroup(workerGroup) + .channelType(channelType()) .maxInboundMessageSize(maxInboundMessageSize) .keepAliveTime(keepAliveTimeSec, TimeUnit.SECONDS) .keepAliveTimeout(keepAliveTimeoutSec, TimeUnit.SECONDS) @@ -146,6 +165,22 @@ public class EdgeGrpcClient implements EdgeRpcClient { return EdgeVersionComparator.getNewestEdgeVersion(); } + private static EventLoopGroup createWorkerGroup() { + DefaultThreadFactory threadFactory = new DefaultThreadFactory("edge-grpc-worker", true); + return Epoll.isAvailable() ? new EpollEventLoopGroup(1, threadFactory) : new NioEventLoopGroup(1, threadFactory); + } + + private static Class channelType() { + return Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class; + } + + @PreDestroy + public void destroy() { + if (workerGroup != null) { + workerGroup.shutdownGracefully(); + } + } + private StreamObserver initOutputStream(String edgeKey, Consumer onUplinkResponse, Consumer onEdgeUpdate, @@ -162,8 +197,10 @@ public class EdgeGrpcClient implements EdgeRpcClient { serverMaxInboundMessageSize = connectResponseMsg.getMaxInboundMessageSize(); } log.info("[{}] Configuration received: {}", edgeKey, connectResponseMsg.getConfiguration()); + connected = true; onEdgeUpdate.accept(connectResponseMsg.getConfiguration()); } else { + connected = false; log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { EdgeGrpcClient.this.disconnect(true); @@ -186,6 +223,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void onError(Throwable t) { + connected = false; log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { EdgeGrpcClient.this.disconnect(true); @@ -197,6 +235,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void onCompleted() { + connected = false; log.info("[{}] Stream was closed and completed successfully!", edgeKey); } }; @@ -204,6 +243,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { + connected = false; if (!onError) { try { if (inputStream != null) { @@ -236,10 +276,19 @@ public class EdgeGrpcClient implements EdgeRpcClient { } } + @Override + public boolean isConnected() { + return connected; + } + @Override public void sendUplinkMsg(UplinkMsg msg) { uplinkMsgLock.lock(); try { + if (!connected) { + log.debug("Uplink msg is skipped, the cloud session is not established: {}", msg); + return; + } this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) .setUplinkMsg(msg) @@ -253,6 +302,10 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void sendSyncRequestMsg(boolean fullSyncRequired) { uplinkMsgLock.lock(); try { + if (!connected) { + log.debug("Sync request msg is skipped, the cloud session is not established"); + return; + } SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() .setFullSync(fullSyncRequired) .build(); @@ -269,6 +322,10 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { uplinkMsgLock.lock(); try { + if (!connected) { + log.debug("Downlink response msg is skipped, the cloud session is not established: {}", downlinkResponseMsg); + return; + } this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) .setDownlinkResponseMsg(downlinkResponseMsg) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeRpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeRpcClient.java index 267fd2b3f2..d9a05ab2ce 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeRpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeRpcClient.java @@ -34,6 +34,8 @@ public interface EdgeRpcClient { void disconnect(boolean onError) throws InterruptedException; + boolean isConnected(); + void sendSyncRequestMsg(boolean fullSyncRequired); void sendUplinkMsg(UplinkMsg uplinkMsg); diff --git a/common/edge-api/src/test/java/org/thingsboard/edge/rpc/EdgeGrpcClientLeakTest.java b/common/edge-api/src/test/java/org/thingsboard/edge/rpc/EdgeGrpcClientLeakTest.java new file mode 100644 index 0000000000..9fc66ed33e --- /dev/null +++ b/common/edge-api/src/test/java/org/thingsboard/edge/rpc/EdgeGrpcClientLeakTest.java @@ -0,0 +1,168 @@ +/** + * 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.edge.rpc; + +import io.grpc.Server; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.buffer.PooledByteBufAllocator; +import io.grpc.stub.StreamObserver; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.gen.edge.v1.ConnectResponseCode; +import org.thingsboard.server.gen.edge.v1.ConnectResponseMsg; +import org.thingsboard.server.gen.edge.v1.EdgeRpcServiceGrpc; +import org.thingsboard.server.gen.edge.v1.RequestMsg; +import org.thingsboard.server.gen.edge.v1.RequestMsgType; +import org.thingsboard.server.gen.edge.v1.ResponseMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; + +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; + +import static org.junit.jupiter.api.Assertions.fail; + +class EdgeGrpcClientLeakTest { + + // The window in which the default shared event loop group would be destroyed after the channel + // terminates (SharedResourceHolder delays destruction by 1 second). If EdgeGrpcClient ever goes + // back to the shared group, writes after this window hit a terminated executor and every buffer + // committed to grpc-netty's WriteQueue is pinned forever (4112 bytes per message, silent after + // the first RejectedExecutionException). + private static final long SHARED_GROUP_DEATH_WINDOW_MS = 3000; + private static final int MSG_COUNT = 50; + private static final long AWAIT_TIMEOUT_MS = 15_000; + + private Server server; + private EdgeGrpcClient client; + + @Test + void uplinksSentAfterTransportDeathDoNotPinPooledBuffers() throws Exception { + server = NettyServerBuilder.forPort(0) + .addService(new EdgeRpcServiceGrpc.EdgeRpcServiceImplBase() { + @Override + public StreamObserver handleMsgs(StreamObserver outputStream) { + return new StreamObserver<>() { + @Override + public void onNext(RequestMsg requestMsg) { + if (requestMsg.hasConnectRequestMsg()) { + outputStream.onNext(ResponseMsg.newBuilder() + .setConnectResponseMsg(ConnectResponseMsg.newBuilder() + .setResponseCode(ConnectResponseCode.ACCEPTED) + .build()) + .build()); + } + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onCompleted() { + } + }; + } + }) + .build() + .start(); + + client = new EdgeGrpcClient(); + ReflectionTestUtils.setField(client, "rpcHost", "localhost"); + ReflectionTestUtils.setField(client, "rpcPort", server.getPort()); + ReflectionTestUtils.setField(client, "timeoutSecs", 1); + ReflectionTestUtils.setField(client, "keepAliveTimeSec", 10); + ReflectionTestUtils.setField(client, "keepAliveTimeoutSec", 5); + ReflectionTestUtils.setField(client, "maxInboundMessageSize", 4194304); + + client.connect("leakTest", "leakTest", msg -> {}, cfg -> {}, msg -> {}, e -> {}); + await("client to connect", () -> client.isConnected()); + + server.shutdownNow(); + server.awaitTermination(10, TimeUnit.SECONDS); + await("client to observe the transport death", () -> !client.isConnected()); + Thread.sleep(SHARED_GROUP_DEATH_WINDOW_MS); + + long baseline = pinnedBytes(); + @SuppressWarnings("unchecked") + StreamObserver inputStream = (StreamObserver) ReflectionTestUtils.getField(client, "inputStream"); + RequestMsg uplink = RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(UplinkMsg.newBuilder().setUplinkMsgId(1).build()) + .build(); + // Bypasses the connected gate on purpose: this models the check-then-act straggler (and the + // pre-gate retry loop) writing to a stream whose transport is already gone. Exceptions are + // swallowed the same way the production retry loop survives them. + for (int i = 0; i < MSG_COUNT; i++) { + try { + inputStream.onNext(uplink); + } catch (RuntimeException ignored) { + } + } + + long deadline = System.currentTimeMillis() + AWAIT_TIMEOUT_MS; + while (pinnedBytes() > baseline) { + if (System.currentTimeMillis() > deadline) { + fail("Pinned pooled memory did not return to baseline: " + (pinnedBytes() - baseline) + + " bytes retained after " + MSG_COUNT + " uplinks to a dead stream"); + } + Thread.sleep(50); + } + } + + @AfterEach + void tearDown() throws Exception { + if (client != null) { + client.disconnect(true); + client.destroy(); + } + if (server != null) { + server.shutdownNow(); + } + } + + private void await(String what, BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + AWAIT_TIMEOUT_MS; + while (!condition.getAsBoolean()) { + if (System.currentTimeMillis() > deadline) { + fail("Timed out waiting for " + what); + } + Thread.sleep(50); + } + } + + // grpc-netty builds its own PooledByteBufAllocator instances instead of using + // PooledByteBufAllocator.DEFAULT, and the factory that owns them is package private - so they + // have to be pulled out reflectively. Both variants are checked so the assertion holds no matter + // which one the transport picks on this platform/version. + private static long pinnedBytes() { + try { + Class utils = Class.forName("io.grpc.netty.shaded.io.grpc.netty.Utils"); + Method getByteBufAllocator = utils.getDeclaredMethod("getByteBufAllocator", boolean.class); + getByteBufAllocator.setAccessible(true); + long total = 0; + for (boolean forceHeapBuffer : new boolean[]{false, true}) { + PooledByteBufAllocator pooled = (PooledByteBufAllocator) getByteBufAllocator.invoke(null, forceHeapBuffer); + total += pooled.pinnedDirectMemory() + pooled.pinnedHeapMemory(); + } + return total; + } catch (Exception e) { + throw new IllegalStateException("Failed to read the gRPC allocator metrics", e); + } + } + +} From f92065693c1018dfe807cf28cbfa4d11680708aa Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 10 Aug 2026 17:40:33 +0300 Subject: [PATCH 023/213] Create the gRPC worker event loop group eagerly as a final field --- .../java/org/thingsboard/edge/rpc/EdgeGrpcClient.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index e78ca440a6..141cca2250 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -93,7 +93,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private ManagedChannel channel; - private EventLoopGroup workerGroup; + private final EventLoopGroup workerGroup = createWorkerGroup(); private StreamObserver inputStream; @@ -109,9 +109,6 @@ public class EdgeGrpcClient implements EdgeRpcClient { Consumer onDownlink, Consumer onError) { connected = false; - if (workerGroup == null) { - workerGroup = createWorkerGroup(); - } NettyChannelBuilder builder = NettyChannelBuilder.forAddress(rpcHost, rpcPort) .eventLoopGroup(workerGroup) .channelType(channelType()) @@ -176,9 +173,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @PreDestroy public void destroy() { - if (workerGroup != null) { - workerGroup.shutdownGracefully(); - } + workerGroup.shutdownGracefully(); } private StreamObserver initOutputStream(String edgeKey, From 0ac6ddb50d361af6ed0a5eb114c98c8fe98be3ab Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 11 Aug 2026 10:39:28 +0300 Subject: [PATCH 024/213] Gate uplink sends on a live stream instead of a completed handshake --- .../org/thingsboard/edge/rpc/EdgeGrpcClient.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index 141cca2250..2237e06f43 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -99,6 +99,8 @@ public class EdgeGrpcClient implements EdgeRpcClient { private volatile boolean connected; + private volatile boolean streamActive; + private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); @Override @@ -109,6 +111,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { Consumer onDownlink, Consumer onError) { connected = false; + streamActive = false; NettyChannelBuilder builder = NettyChannelBuilder.forAddress(rpcHost, rpcPort) .eventLoopGroup(workerGroup) .channelType(channelType()) @@ -147,6 +150,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); log.info("[{}] Sending a connect request to the TB!", edgeKey); this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + streamActive = true; this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) .setConnectRequestMsg(ConnectRequestMsg.newBuilder() @@ -219,6 +223,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void onError(Throwable t) { connected = false; + streamActive = false; log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { EdgeGrpcClient.this.disconnect(true); @@ -231,6 +236,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void onCompleted() { connected = false; + streamActive = false; log.info("[{}] Stream was closed and completed successfully!", edgeKey); } }; @@ -239,6 +245,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { connected = false; + streamActive = false; if (!onError) { try { if (inputStream != null) { @@ -280,7 +287,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void sendUplinkMsg(UplinkMsg msg) { uplinkMsgLock.lock(); try { - if (!connected) { + if (!streamActive) { log.debug("Uplink msg is skipped, the cloud session is not established: {}", msg); return; } @@ -297,7 +304,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void sendSyncRequestMsg(boolean fullSyncRequired) { uplinkMsgLock.lock(); try { - if (!connected) { + if (!streamActive) { log.debug("Sync request msg is skipped, the cloud session is not established"); return; } @@ -317,7 +324,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { uplinkMsgLock.lock(); try { - if (!connected) { + if (!streamActive) { log.debug("Downlink response msg is skipped, the cloud session is not established: {}", downlinkResponseMsg); return; } From b31845e4beecfbb684b068e265604e8d5f45c152 Mon Sep 17 00:00:00 2001 From: Dmytro Pinkevych <49400214+pinkevmladchy@users.noreply.github.com> Date: Thu, 13 Aug 2026 16:43:01 +0300 Subject: [PATCH 025/213] Merge pull request #16028 from pinkevmladchy/iot-hub-built-in-items Open built-in IoT Hub items locally instead of installing duplicates --- ui-ngx/src/app/core/http/widget.service.ts | 2 +- .../dashboard-widget-select.component.html | 13 +- .../dashboard-widget-select.component.ts | 41 ++++- .../iot-hub/iot-hub-actions.service.ts | 79 +++++++++- .../iot-hub-add-item-dialog.component.ts | 15 ++ .../iot-hub/iot-hub-built-in.service.ts | 146 ++++++++++++++++++ .../iot-hub-install-dialog.component.html | 2 +- .../iot-hub-install-dialog.component.ts | 11 ++ .../iot-hub/iot-hub-item-card.component.html | 32 ++-- .../iot-hub/iot-hub-item-card.component.ts | 13 +- .../iot-hub-item-detail-dialog.component.html | 28 ++-- .../iot-hub-item-detail-dialog.component.ts | 32 ++++ .../home/components/iot-hub/iot-hub-utils.ts | 52 ++++++- .../home-page/iot-hub-widget.component.html | 20 ++- .../lib/home-page/iot-hub-widget.component.ts | 7 +- .../models/iot-hub/iot-hub-version.models.ts | 8 + .../assets/locale/locale.constant-en_US.json | 7 + 17 files changed, 457 insertions(+), 51 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-built-in.service.ts diff --git a/ui-ngx/src/app/core/http/widget.service.ts b/ui-ngx/src/app/core/http/widget.service.ts index 06a6c86ddd..e4e50cc830 100644 --- a/ui-ngx/src/app/core/http/widget.service.ts +++ b/ui-ngx/src/app/core/http/widget.service.ts @@ -188,7 +188,7 @@ export class WidgetService { } public getWidgetType(fullFqn: string, config?: RequestConfig): Observable { - return this.http.get(`/api/widgetType?fqn=${fullFqn}`, + return this.http.get(`/api/widgetType?fqn=${encodeURIComponent(fullFqn)}`, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html index 7d2ea9cdb5..6da41a9878 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html @@ -370,7 +370,8 @@ - +
{{item.name}} @@ -405,10 +406,12 @@ {{ 'iot-hub.installed' | translate }} } - - file_download - {{ item.totalInstallCount | shortNumber }} - + @if (!isIotHubWidgetBuiltIn(item)) { + + file_download + {{ item.totalInstallCount | shortNumber }} + + }
diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index 3034cee011..46d4e06e91 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -39,7 +39,14 @@ import { ItemType, FilterParamInfo, WidgetCategory } from '@shared/models/iot-hu import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; -import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup, resolveIotHubItemImageUrl } from '@home/components/iot-hub/iot-hub-utils'; +import { + filterIotHubItemsBySearch, + groupIotHubFilterItems, + IotHubFilterGroup, + isBuiltInItem, + resolveIotHubItemImageUrl +} from '@home/components/iot-hub/iot-hub-utils'; +import { IotHubBuiltInService } from '@home/components/iot-hub/iot-hub-built-in.service'; type selectWidgetMode = 'installed' | 'iotHub'; type installedSubMode = 'default' | 'allWidgets'; @@ -278,6 +285,7 @@ export class DashboardWidgetSelectComponent { constructor(private widgetsService: WidgetService, private iotHubApiService: IotHubApiService, private iotHubActions: IotHubActionsService, + private iotHubBuiltInService: IotHubBuiltInService, private translate: TranslateService, private cd: ChangeDetectorRef) { @@ -494,6 +502,13 @@ export class DashboardWidgetSelectComponent { } return; } + if (isBuiltInItem(item)) { + // Built-in widgets ship with the platform: pick the local widget type matched by fqn + // instead of installing a duplicate, exactly like an already installed item. + this.selectBuiltInWidget(item); + return; + } + // Built-in items never reach the dialog (they return above), so anything added from it installs. this.iotHubActions.openItemDetail(item, undefined, undefined, 'add').subscribe(result => { if (result?.action === 'add') { this.installAndAddWidget(result.item); @@ -505,6 +520,10 @@ export class DashboardWidgetSelectComponent { return this.installedWidgets?.some(i => i.itemId === item.itemId) ?? false; } + isIotHubWidgetBuiltIn(item: MpItemVersionView): boolean { + return isBuiltInItem(item); + } + getIotHubItemImage(item: MpItemVersionView): string | null { return resolveIotHubItemImageUrl(item, this.iotHubApiService); } @@ -737,6 +756,26 @@ export class DashboardWidgetSelectComponent { this.cd.markForCheck(); } + private selectBuiltInWidget(item: MpItemVersionView): void { + this.iotHubBuiltInService.resolveLocalWidgetTypeInfo(item).subscribe(lookup => { + if (lookup.value) { + this.widgetSelected.emit(this.toWidgetInfo(lookup.value)); + return; + } + if (lookup.failed) { + // Existence is unknown — installing now could duplicate a widget that is still there. + this.iotHubActions.showBuiltInLookupFailed(item); + return; + } + // The local copy is gone (e.g. deleted by a sysadmin) — installing is the only way back. + this.iotHubActions.confirmInstallMissingBuiltIn(item).subscribe(confirmed => { + if (confirmed) { + this.installAndAddWidget(item); + } + }); + }); + } + private installAndAddWidget(item: MpItemVersionView): void { const versionId = item.id as string; this.iotHubApiService.installItemVersion(versionId, { ignoreLoading: true }).subscribe({ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 73e627fbe6..cd3d48d5d5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -17,6 +17,7 @@ import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of, EMPTY } from 'rxjs'; +import { map, switchMap } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; import { DialogService } from '@core/services/dialog.service'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -30,6 +31,15 @@ import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component'; import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; +import { IotHubBuiltInService } from './iot-hub-built-in.service'; +import { isBuiltInItem } from './iot-hub-utils'; + +/** + * What `openBuiltInOrConfirmInstall` did with a built-in item: 'handled' means nothing is left to do + * (the local copy was opened, or the user was told why it could not be), while 'install-requested' + * means the component really is absent and the user asked for it to be installed. + */ +export type IotHubBuiltInAction = 'handled' | 'install-requested'; @Injectable() export class IotHubActionsService { @@ -37,7 +47,8 @@ export class IotHubActionsService { constructor( private dialog: MatDialog, private dialogService: DialogService, - private translate: TranslateService + private translate: TranslateService, + private builtInService: IotHubBuiltInService ) {} openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, @@ -72,7 +83,67 @@ export class IotHubActionsService { }).afterClosed(); } + /** + * Runs the primary action of an item: built-in content is opened locally (never installed), + * device packages are connected, everything else goes through the install dialog. + */ installItem(item: MpItemVersionView): Observable { + if (isBuiltInItem(item)) { + return this.openOrInstallBuiltIn(item); + } + return this.runInstall(item); + } + + /** Opens the local copy of a built-in item, or asks to install it when it really is absent. */ + openBuiltInOrConfirmInstall(item: MpItemVersionView): Observable { + return this.builtInService.openLocalComponent(item).pipe( + switchMap(outcome => { + switch (outcome) { + case 'missing': + return this.confirmInstallMissingBuiltIn(item).pipe( + map((confirmed): IotHubBuiltInAction => confirmed ? 'install-requested' : 'handled') + ); + case 'failed': + this.showBuiltInLookupFailed(item); + return of('handled'); + default: + // 'opened' or 'cancelled' — the component is in place either way, so never install. + return of('handled'); + } + }) + ); + } + + /** + * Asks whether to install a built-in item whose local copy is gone — the component the Hub entry + * mirrors was deleted from this instance, so installing is the only way to get it back. + */ + confirmInstallMissingBuiltIn(item: MpItemVersionView): Observable { + return this.dialogService.confirm( + this.translate.instant('iot-hub.built-in-missing-title'), + this.translate.instant('iot-hub.built-in-missing-text', { name: item?.name }), + this.translate.instant('action.cancel'), + this.translate.instant('iot-hub.install') + ); + } + + /** Reports that the local copy could not be checked — nothing was opened and nothing installed. */ + showBuiltInLookupFailed(item: MpItemVersionView): void { + this.dialogService.alert( + this.translate.instant('iot-hub.built-in-lookup-failed-title'), + this.translate.instant('iot-hub.built-in-lookup-failed-text', { name: item?.name }) + ); + } + + private openOrInstallBuiltIn(item: MpItemVersionView): Observable { + return this.openBuiltInOrConfirmInstall(item).pipe( + // The confirmation inside is the only one the user gets: install starts immediately, + // and opening the component is a separate click once it is back in the library. + switchMap(action => action === 'install-requested' ? this.runInstall(item, true) : EMPTY) + ); + } + + private runInstall(item: MpItemVersionView, skipConfirm = false): Observable { if (item.type === ItemType.ALARM_RULE) { this.dialogService.alert( this.translate.instant('iot-hub.alarm-rule-install-update-required'), @@ -81,13 +152,13 @@ export class IotHubActionsService { return EMPTY; } if (item.type === ItemType.DEVICE) { - return this.installDevice(item); + return this.openDeviceInstallDialog(item); } return this.dialog.open(TbIotHubInstallDialogComponent, { panelClass: ['tb-dialog'], disableClose: true, autoFocus: false, - data: { item } as IotHubInstallDialogData + data: { item, skipConfirm } as IotHubInstallDialogData }).afterClosed(); } @@ -121,6 +192,8 @@ export class IotHubActionsService { }).afterClosed(); } + // Reached only for items whose action mode is 'connect', i.e. never for built-in content: + // that decision is made once, at the public entry points above. installDevice(item: MpItemVersionView): Observable { return this.openDeviceInstallDialog(item); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts index e83580e271..404ec8ef03 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts @@ -27,6 +27,7 @@ import { DialogService } from '@core/services/dialog.service'; import { TranslateService } from '@ngx-translate/core'; import { EntityId } from '@shared/models/id/entity-id'; import { IotHubActionsService } from './iot-hub-actions.service'; +import { isBuiltInItem } from './iot-hub-utils'; export interface IotHubAddItemDialogData { itemType: ItemType; @@ -73,6 +74,20 @@ export class TbIotHubAddItemDialogComponent extends DialogComponent { + if (action === 'install-requested') { + this.doAddItem(item); + } + }); + return; + } + this.doAddItem(item); + } + + private doAddItem(item: MpItemVersionView): void { if (this.itemType === ItemType.DEVICE) { this.installDeviceItem(item); return; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-built-in.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-built-in.service.ts new file mode 100644 index 0000000000..054bec852f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-built-in.service.ts @@ -0,0 +1,146 @@ +/// +/// 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. +/// + +import { Injectable } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Router } from '@angular/router'; +import { from, Observable, of } from 'rxjs'; +import { catchError, concatMap, first, map, switchMap } from 'rxjs/operators'; +import { WidgetService } from '@core/http/widget.service'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; +import { isValidWidgetFullFqn, WidgetType, WidgetTypeInfo } from '@shared/models/widget.models'; +import { EntityType } from '@shared/models/entity-type.models'; +import { getEntityDetailsPageURL, isNotEmptyStr } from '@core/utils'; + +/** + * Result of looking up the local component a built-in Hub item mirrors. `failed` separates + * "the lookup itself did not answer" (network error, 5xx, no read permission) from "the component + * is not here": only the latter may be offered as an install, otherwise a transient error would + * hand the tenant a duplicate of a component that is still in place. + */ +export interface IotHubLocalLookup { + value: T | null; + failed: boolean; +} + +/** + * Outcome of trying to open the local component of a built-in item. 'cancelled' means the component + * is there but the router did not go — typically a route guard blocked it (unsaved changes) — so + * there is nothing to install and nothing to report. + */ +export type IotHubOpenLocalOutcome = 'opened' | 'cancelled' | 'missing' | 'failed'; + +/** + * Handles IoT Hub items marked `builtIn` — content that already ships inside ThingsBoard. + * Such an item is never installed: its `fqn` is deliberately identical to the fqn of the + * platform's own component, which is used as the match key to reach the local copy. + */ +@Injectable({ + providedIn: 'root' +}) +export class IotHubBuiltInService { + + constructor( + private router: Router, + private widgetService: WidgetService + ) {} + + /** + * Resolves the platform's own widget type mirroring a built-in Hub item, matched by fqn. + * + * There is no API to test a batch of fqns at once — `GET /api/widgetType?fqn=` is per fqn and + * carries the full descriptor, and `/api/widgetTypeFqns` is scoped to a bundle the Hub payload + * does not name — so this must stay a per-item check triggered by a click, never a prefetch + * across a catalogue page. + */ + resolveLocalWidgetType(item: MpItemVersionView): Observable> { + const noMatch: IotHubLocalLookup = { value: null, failed: false }; + const fqn = item?.dataDescriptor?.fqn; + if (!isNotEmptyStr(fqn)) { + // Without a match key nothing was asked of the server, so existence is unknown rather than + // disproven — reporting it as absent would offer an install for a component that is in place. + return of({ value: null, failed: true }); + } + // Hub items carry a bare fqn; platform widget types are addressed by a scoped full fqn. + // Built-in content is system scoped; the tenant scope covers a copy installed into this tenant, + // which matters while the installed-items list a caller filters by is still stale. + const fullFqns = isValidWidgetFullFqn(fqn) ? [fqn] : [`system.${fqn}`, `tenant.${fqn}`]; + return from(fullFqns).pipe( + concatMap(fullFqn => this.widgetService.getWidgetType(fullFqn, { ignoreErrors: true, ignoreLoading: true }).pipe( + map(widgetType => this.lookupResult(widgetType)), + catchError((err: HttpErrorResponse) => of(this.lookupFailure(err))) + )), + // Stop at the first match, and at the first hard failure too: with existence unknown, the + // remaining candidate cannot turn a failure into a trustworthy "not here". + first(lookup => !!lookup.value?.id?.id || lookup.failed, noMatch) + ); + } + + /** Same match, resolved to the info projection widget pickers need (image, description, type). */ + resolveLocalWidgetTypeInfo(item: MpItemVersionView): Observable> { + return this.resolveLocalWidgetType(item).pipe( + switchMap(lookup => lookup.value + ? this.widgetService.getWidgetTypeInfoById(lookup.value.id.id, { ignoreErrors: true, ignoreLoading: true }).pipe( + map(widgetTypeInfo => this.lookupResult(widgetTypeInfo)), + catchError((err: HttpErrorResponse) => of(this.lookupFailure(err))) + ) + : of({ value: null, failed: lookup.failed })) + ); + } + + /** Navigates to the local component a built-in item mirrors, reporting why it could not. */ + openLocalComponent(item: MpItemVersionView): Observable { + return this.resolveLocalComponentUrl(item).pipe( + switchMap(lookup => { + if (!lookup.value) { + return of(lookup.failed ? 'failed' : 'missing'); + } + // The navigation itself can still be refused — a ConfirmOnExitGuard on the page the user is + // leaving, a failing resolver — and reporting it as opened would leave them with the Hub + // dialog closed (it closes on NavigationStart) and nothing opened in its place. + return from(this.router.navigateByUrl(lookup.value)).pipe( + map((navigated): IotHubOpenLocalOutcome => navigated ? 'opened' : 'cancelled'), + catchError(() => of('cancelled')) + ); + }) + ); + } + + private resolveLocalComponentUrl(item: MpItemVersionView): Observable> { + // Only widgets (including SCADA symbol widgets) ship inside the platform today. Other item + // types have no local counterpart to match by fqn, so they count as missing. + if (item?.type !== ItemType.WIDGET) { + return of({ value: null, failed: false }); + } + return this.resolveLocalWidgetType(item).pipe( + map(lookup => ({ + value: lookup.value ? getEntityDetailsPageURL(lookup.value.id.id, EntityType.WIDGET_TYPE) || null : null, + failed: lookup.failed + })) + ); + } + + private lookupResult(value: T | null): IotHubLocalLookup { + return { value: value ?? null, failed: false }; + } + + // A 404 is an answer — the component is not here. Anything else (network error, 5xx, 403) leaves + // existence unknown, and must never be presented to the user as deleted content. + private lookupFailure(err: HttpErrorResponse): IotHubLocalLookup { + return { value: null, failed: err?.status !== 404 }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index ea3774ac11..25c5ca2089 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -117,7 +117,7 @@ } @case ('installing') { -

{{ 'iot-hub.install-confirm-title' | translate:{ name: item.name } }}

+

{{ 'iot-hub.installing-title' | translate:{ name: item.name } }}

{{ 'iot-hub.install-desc' | translate }}

} @case ('success') { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 43ed8d21b4..e4816d19ad 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -60,6 +60,13 @@ interface PendingOverwrite { export interface IotHubInstallDialogData { item: MpItemVersionView; + /** + * Starts installing right away instead of opening on the confirm step. Set by callers that + * already asked the user — e.g. a built-in item whose local copy was deleted — so the user is + * not asked to confirm the same install twice. Ignored when the item needs input first + * (entity selection, rule chain options). + */ + skipConfirm?: boolean; } export type InstallState = @@ -140,6 +147,10 @@ export class TbIotHubInstallDialogComponent extends DialogComponent{{ item.creatorDisplayName }} - · + @if (showInstallCount) { + · + } + } + @if (showInstallCount) { + download + {{ item.totalInstallCount | shortNumber }} } - download - {{ item.totalInstallCount | shortNumber }}
@if (mode === 'add') { @if (isInstalled()) { check{{ 'iot-hub.installed' | translate }} } @else { - + } } @else if (isInstalled()) { @if (isSameVersion()) { @@ -74,7 +78,7 @@ } } @else { - + } } @else { @@ -105,18 +109,22 @@ [class.clickable]="mode !== 'add'" (click)="mode !== 'add' && onCreatorClick($event)" (keyup.enter)="mode !== 'add' && onCreatorClick($event)">{{ item.creatorDisplayName }} - · + @if (showInstallCount) { + · + } + } + @if (showInstallCount) { + + download + {{ item.totalInstallCount | shortNumber }} + } - - download - {{ item.totalInstallCount | shortNumber }} - @if (mode === 'add') { @if (isInstalled()) { check{{ 'iot-hub.installed' | translate }} } @else { - + } } @else if (isInstalled()) { @if (isSameVersion()) { @@ -143,7 +151,7 @@ } } @else { - + } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index 2d9c13d8d7..b2fe9a58f3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -20,6 +20,7 @@ import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.m import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { TranslateService } from '@ngx-translate/core'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { iotHubItemActionLabel, isBuiltInItem } from '@home/components/iot-hub/iot-hub-utils'; @Component({ selector: 'tb-iot-hub-item-card', @@ -29,8 +30,6 @@ import { IotHubApiService } from '@core/http/iot-hub-api.service'; }) export class TbIotHubItemCardComponent { - readonly ItemType = ItemType; - @Input() item: MpItemVersionView; @Input() installedItem: IotHubInstalledItem; @Input() installedItemsCount = 0; @@ -51,6 +50,16 @@ export class TbIotHubItemCardComponent { private iotHubApiService: IotHubApiService ) {} + // Install counters mean nothing for content the tenant already has, so the counter and the + // separator that would dangle next to it are both derived from this one boolean. + get showInstallCount(): boolean { + return !isBuiltInItem(this.item); + } + + get actionLabel(): string { + return iotHubItemActionLabel(this.item, this.mode === 'add' ? 'add' : 'card'); + } + isCompactLayout(): boolean { return this.item.type === ItemType.CALCULATED_FIELD || this.item.type === ItemType.ALARM_RULE diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html index 30d9322dd9..eba34fb30a 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html @@ -30,15 +30,17 @@ {{ getTypeIcon() }} {{ typeTranslations.get(item.type) | translate }} - - - download - {{ item.totalInstallCount | shortNumber }} {{ 'iot-hub.installs' | translate }} - + @if (showInstallCount) { + + + download + {{ item.totalInstallCount | shortNumber }} {{ 'iot-hub.installs' | translate }} + + } update - v {{ item.version }} + {{ versionLabel }} @if (preview) { @@ -318,19 +320,13 @@ @if (mode === 'add' && !isInstalled()) { } @if (!isInstalled() && mode !== 'add') { - @if (item.type === ItemType.DEVICE) { - - } @else { - - } + } @if (isInstalled() && mode !== 'add') {