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 0c9a4fa21d..e650bc5f42 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 @@ -76,7 +76,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; -import java.util.function.Function; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -545,16 +544,22 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i destroySession(toRemove); sessionsById.remove(sessionId); TenantId tenantId = toRemove.getEdge().getTenantId(); - // A newer session on another node may have already claimed this edge and set active=true. - // Clearing the flag here would leave the edge marked inactive while it is in fact connected, - // which silently drops every downlink event that is not queued for offline edges. - // When ownership is unknown (no cache entry) fall through and persist the inactive state. - if (!isOwnedByAnotherNode(edgeId)) { + // The edge may already have been claimed by a newer session - on this node (a replacement that + // landed while this stale callback was tearing its own session down) or on another live node. + // Either way the edge is connected, so none of the disconnect side effects apply: + // - clearing the flag makes saveEdgeEvent drop assignment events until a full sync; + // - a newer lastDisconnectTime would contradict the live session's lastConnectTime; + // - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata, + // so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight + // back, re-creating the dropped-event behaviour through the rule engine. + // Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline + // edge is always marked inactive. + if (!sessions.containsKey(edgeId) && !isOwnedByAnotherNode(edgeId)) { 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); } - long lastDisconnectTs = System.currentTimeMillis(); - save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); cancelScheduleEdgeEventsCheck(edgeId); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -570,10 +575,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - // Only evict if the cache still points at this node. If the edge already reconnected to another - // TB-Core node, that node has overwritten the entry and owns it - evicting here would wipe the live - // owner's claim and defeat the activity-state guard above. - if (isOwnedByThisNode(edgeId)) { + // Only evict if no live session holds this edge on this node any more and the cache still points + // here. If the edge already reconnected - to this node or to another one - that session owns the + // entry, and evicting it would wipe the live owner's claim and defeat the activity-state guard above. + if (!sessions.containsKey(edgeId) && isOwnedByThisNode(edgeId)) { edgeIdServiceIdCache.evict(edgeId); } } @@ -585,6 +590,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i // - entry naming a node that is no longer in the cluster: the edge sessions cache has no TTL by default // (CACHE_SPECS_EDGE_SESSIONS_TTL=0) and is only ever evicted by the owning node, so a node that died // without evicting would otherwise keep the edge marked active forever, with no reconciler to correct it. + // Note this covers a node that is gone, not one that restarted under the same service id - that claim + // still resolves as live, leaving the edge marked active until something reconnects. That errs towards + // queueing edge events rather than dropping them, which is the safe direction. + // This narrows the race rather than closing it: the attribute is plain last-writer-wins, and two nodes can + // still issue their async writes in an order this read cannot see. private boolean isOwnedByAnotherNode(EdgeId edgeId) { TbCacheValueWrapper wrapper = edgeIdServiceIdCache.get(edgeId); if (wrapper == null) { @@ -722,7 +732,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); + // Compare-and-remove: destroy() above is not instantaneous, so the edge may have reconnected and + // put a live session under this id in the meantime. Removing it unconditionally would leave a + // connected edge with no entry in 'sessions', silently no-opping every downlink lookup. + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { @@ -751,11 +764,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return result; } - private void tryToDestroyZombieSessions(List sessionsToRemove, Function removeFunc) { + private void tryToDestroyZombieSessions(List sessionsToRemove, Consumer removeFunc) { for (EdgeGrpcSession toRemove : sessionsToRemove) { log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId()); if (toRemove.destroy()) { - removeFunc.apply(toRemove); + removeFunc.accept(toRemove); } } } 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 7b71c65c9f..512e5cf283 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 @@ -19,6 +19,7 @@ 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.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -29,19 +30,31 @@ import org.thingsboard.server.cache.TbTransactionalCache; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -73,6 +86,15 @@ public class EdgeGrpcServiceTest { @Mock private EdgeContextComponent ctx; + @Mock + private NotificationRuleProcessor ruleProcessor; + + @Mock + private EdgeEventStorageSettings edgeEventStorageSettings; + + @Mock + private ScheduledExecutorService edgeEventProcessingExecutorService; + @InjectMocks private EdgeGrpcService edgeGrpcService; @@ -165,6 +187,82 @@ public class EdgeGrpcServiceTest { verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); } + @Test + public void givenSessionReplacedOnThisNodeAfterRemoval_whenStaleCallbackRuns_thenNoDisconnectSideEffects() { + // The stale callback wins the compare-and-remove, then tearing its own session down takes a while + // (for the Kafka session this stops a consumer). The edge reconnects to THIS node in that gap, so the + // ownership cache legitimately names us and isOwnedByAnotherNode cannot help. None of the disconnect + // side effects may run: not the flag, not the timestamp, not the DISCONNECT_EVENT push. + UUID sessionId = UUID.randomUUID(); + EdgeGrpcSession stale = mock(EdgeGrpcSession.class); + when(stale.getSessionId()).thenReturn(sessionId); + when(stale.getEdge()).thenReturn(edge); + when(stale.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, mock(EdgeGrpcSession.class)); + return true; + }); + lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + sessions().put(edgeId, stale); + + onEdgeDisconnect(sessionId); + + verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); + verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() { + // The DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE, so a rule chain wiring + // Disconnect Event -> Save Attributes would persist active=false back and re-create the bug. + EdgeSessionStub stub = registerSession(); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); + when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); + lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + + onEdgeDisconnect(stub.sessionId()); + + verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + } + + @Test + public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() { + // Also proves the never() assertions above are not vacuous: the push does happen on this path. + EdgeSessionStub stub = registerSession(); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + + onEdgeDisconnect(stub.sessionId()); + + verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull()); + } + + // --- onEdgeConnect ownership publish order --- + + @Test + public void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() { + // Load-bearing ordering: the previous node's onEdgeDisconnect reads this cache entry to decide whether + // to clear the flag, so the claim must be visible before active=true is written. Nothing else pins the + // order, and a tidy-up that groups the save(...) calls together would silently restore the race. + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.getEdge()).thenReturn(edge); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + when(ctx.getRuleProcessor()).thenReturn(ruleProcessor); + when(ctx.getEdgeEventStorageSettings()).thenReturn(edgeEventStorageSettings); + ReflectionTestUtils.setField(edgeGrpcService, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + when(edgeEventProcessingExecutorService.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) + .thenAnswer(invocation -> mock(ScheduledFuture.class)); + + ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeConnect", edgeId, session); + + InOrder inOrder = inOrder(edgeIdServiceIdCache, tsSubService); + inOrder.verify(edgeIdServiceIdCache).put(edgeId, THIS_NODE); + inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite())); + } + // --- service-id cache eviction guard --- @Test @@ -198,6 +296,23 @@ public class EdgeGrpcServiceTest { ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); } + private EdgeSessionStub registerSession() { + UUID sessionId = UUID.randomUUID(); + sessions().put(edgeId, sessionFor(sessionId)); + return new EdgeSessionStub(sessionId); + } + + private record EdgeSessionStub(UUID sessionId) { + } + + private ArgumentMatcher activeStateWrite() { + return request -> request != null + && edgeId.equals(request.getEntityId()) + && request.getEntries().stream().anyMatch(entry -> + ACTIVITY_STATE.equals(entry.getKey()) + && Boolean.TRUE.equals(entry.getBooleanValue().orElse(null))); + } + private EdgeGrpcSession sessionFor(UUID sessionId) { EdgeGrpcSession session = mock(EdgeGrpcSession.class); when(session.getSessionId()).thenReturn(sessionId);