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..9f9c315a2d 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
@@ -73,10 +73,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;
@@ -303,13 +304,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);
+ 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 {
@@ -317,7 +315,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
} finally {
newEventLock.unlock();
}
- cancelScheduleEdgeEventsCheck(edgeId);
+ destroySession(toRemove);
+ toRemove.cleanUp();
}
}
@@ -358,16 +357,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 {
@@ -383,9 +378,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
long lastConnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs);
pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT);
- cancelScheduleEdgeEventsCheck(edgeId);
edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE);
scheduleEdgeEventsCheck(edgeGrpcSession);
+ if (replaced != null) {
+ destroySession(replaced);
+ }
}
private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) {
@@ -447,54 +444,73 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
EdgeId edgeId = session.getEdge().getId();
TenantId tenantId = session.getEdge().getTenantId();
- cancelScheduleEdgeEventsCheck(edgeId);
+ // 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(
+ () -> processEvents(session, edgeId, tenantId),
+ ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS));
+ log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId());
+ return current;
+ });
+ }
- if (sessions.containsKey(edgeId)) {
- ScheduledFuture> edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> {
- 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);
+ 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 {
+ @Override
+ public void onFailure(Throwable t) {
+ log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t);
scheduleEdgeEventsCheck(session);
}
- } else {
- scheduleEdgeEventsCheck(session);
- }
- } finally {
- newEventLock.unlock();
+ }, ctx.getGrpcCallbackExecutorService());
+ } else {
+ scheduleEdgeEventsCheck(session);
}
- } catch (Exception e) {
- log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
+ } else {
+ scheduleEdgeEventsCheck(session);
}
- }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS);
- sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask);
- 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());
+ } finally {
+ newEventLock.unlock();
+ }
+ } catch (Exception e) {
+ log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
}
}
@@ -528,21 +544,11 @@ 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);
- // Claim-once removal: get() and remove() are not atomic, so a session that was replaced between the
- // two would otherwise be dropped from the map, torn down and marked inactive by this stale callback
- // even though it is the live one. Losing the race means this callback owns nothing - fall through to
- // the stale-session branch below.
- if (current != null && current.getSessionId().equals(sessionId) && sessions.remove(edgeId, current)) {
- EdgeGrpcSession toRemove = current;
- 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);
TenantId tenantId = toRemove.getEdge().getTenantId();
// A newer session on another node may have already claimed this edge and set active=true.
@@ -554,8 +560,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
}
long lastDisconnectTs = System.currentTimeMillis();
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);
+ destroySession(toRemove);
} else {
log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId);
EdgeGrpcSession stale = sessionsById.remove(sessionId);
@@ -570,10 +576,11 @@ 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 the cache still points at this node and no live session for this edge is left here.
+ // If the edge already reconnected to another TB-Core node, that node has overwritten the entry and owns it;
+ // if a newer session on this node replaced a stale one, that session owns it - evicting in either case
+ // would wipe the live owner's claim and defeat the activity-state guard above.
+ if (!sessions.containsKey(edgeId) && isOwnedByThisNode(edgeId)) {
edgeIdServiceIdCache.evict(edgeId);
}
}
@@ -603,6 +610,59 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return wrapper != null && serviceInfoProvider.getServiceId().equals(wrapper.get());
}
+ /**
+ * 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<>();
+ sessions.compute(edgeId, (id, current) -> {
+ replaced.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return session;
+ });
+ 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<>();
+ sessions.compute(edgeId, (id, current) -> {
+ if (current == null || !shouldDetach.test(current)) {
+ return current;
+ }
+ detached.set(current);
+ cancelScheduleEdgeEventsCheck(edgeId);
+ return null;
+ });
+ 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,7 +782,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private void cleanupZombieSessions() {
try {
- tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId()));
+ // 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 -> {
@@ -751,11 +814,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/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java
new file mode 100644
index 0000000000..8b471d0548
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java
@@ -0,0 +1,325 @@
+// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
+// SPDX-License-Identifier: Apache-2.0
+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);
+ }
+
+}
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 80730f9f53..99f8d0b5d5 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
@@ -134,17 +134,14 @@ public class EdgeGrpcServiceTest {
@Test
public void givenSessionReplacedDuringDisconnect_whenStaleCallbackRuns_thenLiveSessionKept() {
- // Reproduces the get()/remove() interleaving on a single node: onEdgeConnect swaps in a new session
- // right after the stale callback's id check passes. The stale callback must not evict or tear down
- // the live session, nor clear the activity state.
+ // onEdgeConnect has already swapped in a new session on this node when the stale callback runs.
+ // The check-and-remove is a single atomic step against the same map that onEdgeConnect writes
+ // through, so the swap can only land before or after it. The stale callback must not evict or
+ // tear down the live session, nor clear the activity state.
UUID staleSessionId = UUID.randomUUID();
EdgeGrpcSession live = mock(EdgeGrpcSession.class);
- EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
- when(stale.getSessionId()).thenAnswer(invocation -> {
- sessions().put(edgeId, live);
- return staleSessionId;
- });
- sessions().put(edgeId, stale);
+ when(live.getSessionId()).thenReturn(UUID.randomUUID());
+ sessions().put(edgeId, live);
onEdgeDisconnect(staleSessionId);