From 03df2a333ab0aad89f64d8ff397addcdf81e98e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 28 Aug 2026 12:08:27 +0300 Subject: [PATCH 1/3] Keep the edge event check alive when an edge reconnects during session teardown --- .../service/edge/rpc/EdgeGrpcService.java | 192 +++++++++++------- 1 file changed, 115 insertions(+), 77 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 e1211c53a7..4de478fe34 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 @@ -83,10 +83,11 @@ 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.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; -import java.util.function.Function; +import java.util.function.Predicate; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -310,13 +311,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession session = sessions.get(edgeId); - if (session != null && session.isConnected()) { + EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); - destroySession(session); - session.cleanUp(); - sessions.remove(edgeId); - sessionsById.remove(session.getSessionId()); + sessionsById.remove(toRemove.getSessionId()); final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -324,7 +322,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - cancelScheduleEdgeEventsCheck(edgeId); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); + toRemove.cleanUp(); } } @@ -365,16 +365,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i Edge edge = edgeGrpcSession.getEdge(); TenantId tenantId = edge.getTenantId(); log.info("[{}][{}] edge [{}] connected successfully.", tenantId, edgeGrpcSession.getSessionId(), edgeId); - if (sessions.containsKey(edgeId)) { - EdgeGrpcSession existing = sessions.get(edgeId); - if (existing != null) { - log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), existing.getSessionId(), edgeId); - destroySession(existing); - sessionsById.remove(existing.getSessionId()); - } - } - sessions.put(edgeId, edgeGrpcSession); + EdgeGrpcSession replaced = attachSession(edgeId, edgeGrpcSession); sessionsById.put(edgeGrpcSession.getSessionId(), edgeGrpcSession); + if (replaced != null) { + log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), replaced.getSessionId(), edgeId); + sessionsById.remove(replaced.getSessionId()); + } final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -387,9 +383,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs); edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); + if (replaced != null) { + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(replaced); + } } private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) { @@ -451,55 +450,62 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - cancelScheduleEdgeEventsCheck(edgeId); - - if (sessions.containsKey(edgeId)) { - ScheduledFuture edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> { + Runnable edgeEventCheck = () -> { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, true); } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); } else { scheduleEdgeEventsCheck(session); } - } finally { - newEventLock.unlock(); + } else { + scheduleEdgeEventsCheck(session); } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } finally { + newEventLock.unlock(); } - }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS); - sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask); + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + }; + + // arm the next check only while this exact session is still the current one, atomically with + // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the + // re-arm nor cancel a check that belongs to a session other than the one it is tearing down + sessions.compute(edgeId, (id, current) -> { + if (current != session) { + log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]", + tenantId, edgeId.getId()); + return current; + } + cancelScheduleEdgeEventsCheck(edgeId); + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); - } else { - log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]", - tenantId, edgeId.getId()); - } + return current; + }); } private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { @@ -532,24 +538,20 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void onEdgeDisconnect(Edge edge, UUID sessionId) { EdgeId edgeId = edge.getId(); log.info("[{}][{}] edge disconnected!", edgeId, sessionId); - EdgeGrpcSession current = sessions.get(edgeId); - if (current != null && current.getSessionId().equals(sessionId)) { - EdgeGrpcSession toRemove = sessions.remove(edgeId); - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - sessionNewEvents.remove(edgeId); - } finally { - newEventLock.unlock(); - } - destroySession(toRemove); + EdgeGrpcSession toRemove = detachSession(edgeId, current -> current.getSessionId().equals(sessionId)); + if (toRemove != null) { + // sessionNewEvents is deliberately left as is: clearing it here could wipe the flag a + // reconnecting session has just set, and updateSessionEventsFlag only lifts FALSE, not a + // missing entry, which would leave the check loop idle forever. deleteEdge still clears it sessionsById.remove(sessionId); + edgeIdServiceIdCache.evict(edgeId); TenantId tenantId = toRemove.getEdge().getTenantId(); - save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); + save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); + pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); EdgeGrpcSession stale = sessionsById.remove(sessionId); @@ -564,7 +566,41 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - edgeIdServiceIdCache.evict(edgeId); + } + + /** + * Registers the session as the current one for the edge and cancels the edge event check armed by + * the session it replaces, as a single atomic step. Returns the replaced session, or null if there + * was none - the caller is responsible for destroying it outside of this critical section. + */ + private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { + AtomicReference replaced = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + replaced.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return session; + }); + return replaced.get(); + } + + /** + * Detaches the edge's registered session and cancels its edge event check as a single atomic step, + * but only if that session satisfies shouldDetach. Returns the detached session, or null if the + * predicate rejected it - most importantly when another session has taken the edge over in the + * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose + * the check it has just armed. The caller destroys the returned session outside the atomic step. + */ + private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { + AtomicReference detached = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + if (current == null || !shouldDetach.test(current)) { + return current; + } + detached.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return null; + }); + return detached.get(); } private void destroySession(EdgeGrpcSession session) { @@ -686,7 +722,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); + // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer + // session must not be evicted by the cleanup of the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { @@ -715,11 +753,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); } } } From 11fe42de7aa596c02ad161d54e2b34459bf73e08 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 12:07:21 +0300 Subject: [PATCH 2/3] Keep the edge event check and its new events flag with the session that owns the edge --- .../service/edge/rpc/EdgeGrpcService.java | 126 +++++++++++------- 1 file changed, 77 insertions(+), 49 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 4de478fe34..5fdd67e0b3 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 @@ -311,7 +311,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + EdgeGrpcSession toRemove = detachSession(edgeId); if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); sessionsById.remove(toRemove.getSessionId()); @@ -322,7 +322,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); toRemove.cleanUp(); } @@ -386,7 +385,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); if (replaced != null) { - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(replaced); } } @@ -450,47 +448,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - Runnable edgeEventCheck = () -> { - try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); - } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } - } else { - scheduleEdgeEventsCheck(session); - } - } finally { - newEventLock.unlock(); - } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); - } - }; - // arm the next check only while this exact session is still the current one, atomically with // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the // re-arm nor cancel a check that belongs to a session other than the one it is tearing down @@ -501,13 +458,66 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return current; } cancelScheduleEdgeEventsCheck(edgeId); - sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule( + () -> processEvents(session, edgeId, tenantId), ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); return current; }); } + private void processEvents(EdgeGrpcSession session, EdgeId edgeId, TenantId tenantId) { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + if (sessions.get(edgeId) != session) { + log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]", + tenantId, edgeId.getId()); + return; + } + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + sessionNewEvents.put(edgeId, true); + } finally { + newEventLock.unlock(); + } + } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); + } else { + scheduleEdgeEventsCheck(session); + } + } else { + scheduleEdgeEventsCheck(session); + } + } finally { + newEventLock.unlock(); + } + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + } + private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { boolean isMigrationProcessed = edgeEventsMigrationProcessed.getOrDefault(edgeId, Boolean.FALSE); if (!isMigrationProcessed) { @@ -550,7 +560,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -572,6 +581,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i * Registers the session as the current one for the edge and cancels the edge event check armed by * the session it replaces, as a single atomic step. Returns the replaced session, or null if there * was none - the caller is responsible for destroying it outside of this critical section. + *

+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of + * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession}, + * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or + * acquiring the per-edge new events lock - has to be done by the caller once compute has returned. */ private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { AtomicReference replaced = new AtomicReference<>(); @@ -583,12 +597,19 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return replaced.get(); } + private EdgeGrpcSession detachSession(EdgeId edgeId) { + return detachSession(edgeId, s -> true); + } + /** * Detaches the edge's registered session and cancels its edge event check as a single atomic step, * but only if that session satisfies shouldDetach. Returns the detached session, or null if the * predicate rejected it - most importantly when another session has taken the edge over in the * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose * the check it has just armed. The caller destroys the returned session outside the atomic step. + *

+ * The remapping function is subject to the same "cheap non-blocking work only" rule as + * {@link #attachSession(EdgeId, EdgeGrpcSession)}. */ private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { AtomicReference detached = new AtomicReference<>(); @@ -603,6 +624,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return detached.get(); } + /** + * Stops the session's edge event consumer and shuts down its executor, collecting the session for a + * later retry if that fails. This can block for seconds - {@code KafkaEdgeGrpcSession.destroy()} + * gives the consumer executor up to 5s to terminate - so it must never be called from inside a + * {@link #sessions} remapping function. + */ private void destroySession(EdgeGrpcSession session) { try (session) { if (!session.destroy()) { @@ -722,9 +749,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer - // session must not be evicted by the cleanup of the one it replaced - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); + // detach by identity: the edge may have reconnected since the zombie scan, and that newer + // session must neither be evicted nor have its edge event check cancelled by the cleanup of + // the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> detachSession(s.getEdge().getId(), current -> current == s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { From a0c6bd4416be26f12ff9ef43488c2bf996c047e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 12:07:22 +0300 Subject: [PATCH 3/3] Add EdgeGrpcService tests for the edge session reconnect race --- .../rpc/EdgeGrpcServiceReconnectTest.java | 338 ++++++++++++++++++ 1 file changed, 338 insertions(+) create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java new file mode 100644 index 0000000000..8b90004e25 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java @@ -0,0 +1,338 @@ +/** + * 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 com.google.common.util.concurrent.Futures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; +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.TenantId; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; +import org.thingsboard.server.queue.TbQueueConsumer; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Covers the reconnect race between a session that is being torn down and the session that has already + * taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new + * events flag of the session that replaced it. + */ +class EdgeGrpcServiceReconnectTest { + + // long enough that an armed check never actually fires during a test + private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; + private static final String THIS_NODE = "test-core"; + + private EdgeGrpcService service; + private ScheduledExecutorService edgeEventProcessingExecutorService; + private TbTransactionalCache edgeIdServiceIdCache; + + private TenantId tenantId; + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + tenantId = TenantId.fromUUID(UUID.randomUUID()); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(tenantId); + edge.setName("test-edge"); + + EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); + ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); + + GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); + // run future callbacks inline so the re-arm is observable without waiting on a pool + doAnswer(invocation -> { + invocation.getArgument(0, Runnable.class).run(); + return null; + }).when(grpcCallbackExecutorService).execute(any()); + + EdgeContextComponent ctx = mock(EdgeContextComponent.class); + when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); + when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); + when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); + + TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + + edgeIdServiceIdCache = mock(TbTransactionalCache.class); + // this node is the recorded owner of the edge, which is what a live local session implies + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); + + service = new EdgeGrpcService(); + ReflectionTestUtils.setField(service, "ctx", ctx); + ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); + ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); + ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); + ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); + ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + } + + @AfterEach + void tearDown() { + edgeEventProcessingExecutorService.shutdownNow(); + } + + @Test + void checkIsArmedForTheCurrentSession() { + EdgeGrpcSession session = newSession(); + sessions().put(edgeId, session); + + scheduleEdgeEventsCheck(session); + + ScheduledFuture armed = edgeEventChecks().get(edgeId); + assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); + assertThat(armed.isCancelled()).isFalse(); + } + + @Test + void checkIsNotArmedForASupersededSession() { + EdgeGrpcSession current = newSession(); + EdgeGrpcSession superseded = newSession(); + sessions().put(edgeId, current); + scheduleEdgeEventsCheck(current); + ScheduledFuture armedByCurrent = edgeEventChecks().get(edgeId); + + scheduleEdgeEventsCheck(superseded); + + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the superseded session must neither cancel nor replace the current session's check") + .isSameAs(armedByCurrent); + assertThat(armedByCurrent.isCancelled()).isFalse(); + } + + @Test + void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + ScheduledFuture armedCheck = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(session); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); + assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); + verify(edgeIdServiceIdCache).evict(edgeId); + verify(session).destroy(); + } + + @Test + void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { + EdgeGrpcSession first = newSession(); + onEdgeConnect(first); + // the edge reconnects before the gRPC stream of the first session is closed + EdgeGrpcSession second = newSession(); + onEdgeConnect(second); + ScheduledFuture armedBySecond = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(first); + + assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); + assertThat(sessionsById()).containsKey(second.getSessionId()); + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the check armed by the reconnected session survives the teardown of the one it replaced") + .isSameAs(armedBySecond); + assertThat(armedBySecond.isCancelled()).isFalse(); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + void disconnectDoesNotClearTheNewEventsFlag() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + assertThat(newEvents()).containsEntry(edgeId, true); + + onEdgeDisconnect(session); + + assertThat(newEvents()) + .as("clearing the flag here would wipe the one a reconnecting session has just raised") + .containsEntry(edgeId, true); + } + + @Test + void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { + EdgeGrpcSession session = newSession(); + when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); + sessions().put(edgeId, session); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + processEvents(session); + + assertThat(newEvents()).containsEntry(edgeId, false); + verify(session).processHighPriorityEvents(); + verify(session).processEdgeEvents(); + assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); + } + + @Test + void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { + EdgeGrpcSession superseded = newSession(); + EdgeGrpcSession current = newSession(); + sessions().put(edgeId, current); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + // cancel(true) cannot stop a check that has already started, so it runs against the old session + processEvents(superseded); + + assertThat(newEvents()) + .as("consuming the flag here would leave the reconnected session with nothing to fetch") + .containsEntry(edgeId, true); + verify(superseded, never()).processHighPriorityEvents(); + verify(superseded, never()).processEdgeEvents(); + assertThat(edgeEventChecks()).doesNotContainKey(edgeId); + } + + @Test + void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + when(zombie.destroy()).thenReturn(true); + sessions().put(edgeId, zombie); + scheduleEdgeEventsCheck(zombie); + ScheduledFuture armedByZombie = edgeEventChecks().get(edgeId); + + cleanupZombieSessions(); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(armedByZombie.isCancelled()) + .as("the removed zombie must not leave an armed check behind") + .isTrue(); + } + + @Test + void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + EdgeGrpcSession reconnected = newSession(); + sessions().put(edgeId, zombie); + // the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up + when(zombie.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, reconnected); + scheduleEdgeEventsCheck(reconnected); + return true; + }); + + cleanupZombieSessions(); + + assertThat(sessions().get(edgeId)).isSameAs(reconnected); + ScheduledFuture armedByReconnected = edgeEventChecks().get(edgeId); + assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); + assertThat(armedByReconnected.isCancelled()).isFalse(); + } + + private EdgeGrpcSession newSession() { + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + stubSession(session); + return session; + } + + private KafkaEdgeGrpcSession newZombieSession() { + KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); + stubSession(session); + @SuppressWarnings("unchecked") + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + @SuppressWarnings("unchecked") + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(consumer.isStopped()).thenReturn(false); + when(session.getConsumer()).thenReturn(consumerManager); + return session; + } + + private void stubSession(EdgeGrpcSession session) { + when(session.getEdge()).thenReturn(edge); + when(session.getTenantId()).thenReturn(tenantId); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.isConnected()).thenReturn(false); + when(session.destroy()).thenReturn(true); + } + + private void onEdgeConnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); + } + + private void onEdgeDisconnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); + } + + private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); + } + + private void processEvents(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); + } + + private void cleanupZombieSessions() { + ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); + } + + private ConcurrentMap sessions() { + return field("sessions"); + } + + private ConcurrentMap sessionsById() { + return field("sessionsById"); + } + + private ConcurrentMap> edgeEventChecks() { + return field("sessionEdgeEventChecks"); + } + + private Map newEvents() { + return field("sessionNewEvents"); + } + + private ConcurrentMap migrationProcessed() { + return field("edgeEventsMigrationProcessed"); + } + + @SuppressWarnings("unchecked") + private T field(String name) { + return (T) ReflectionTestUtils.getField(service, name); + } + +}