diff --git a/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java b/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java index 328ab2d61b..15859394f9 100644 --- a/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java +++ b/common/integration/cluster-integration-api/src/main/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationService.java @@ -23,6 +23,7 @@ import org.thingsboard.server.gen.integration.ToIntegrationExecutorDownlinkMsg; import org.thingsboard.server.gen.integration.ToIntegrationExecutorNotificationMsg; import org.thingsboard.server.queue.TbQueueConsumer; import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.discovery.QueueKey; import org.thingsboard.server.queue.discovery.TbApplicationEventListener; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; @@ -34,6 +35,7 @@ import org.thingsboard.server.queue.util.TbPackCallback; import org.thingsboard.server.queue.util.TbPackProcessingContext; import org.thingsboard.server.service.cache.IntegrationExecutorCacheStartupService; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; @@ -125,39 +127,39 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener protected void onTbApplicationEvent(PartitionChangeEvent event) { log.debug("Received partition change event: {}", event); // Always enqueue first, then drain: the drain below must see this event. Enqueueing only while - // !started dropped every partition change that arrived after startup, so a node kept the snapshot + // !started dropped every partition change that arrived after startup, so a node kept the partitions // it drained at startup forever and singleton integrations ran twice (or nowhere) after a rollout. pendingEvents.add(event); if (!started) { log.debug("Integration Executor not started yet, event queued for later: {}", event); return; // doStartup() will drain the queue } - // Either already started or just became started - drain and process the latest pending + // Either already started or just became started - drain and process the pending changes drainPendingEvents(); } - // Synchronized so that the startup thread and an event thread cannot process two snapshots concurrently - // and push them to subscribeEventsMap in reverse order, which would leave the older snapshot applied. + // Synchronized so that the startup thread and an event thread cannot process two drains concurrently + // and push them to subscribeEventsMap in reverse order, which would leave older partitions applied. private synchronized void drainPendingEvents() { - // Each PartitionChangeEvent carries a full partition snapshot for TB_INTEGRATION_EXECUTOR, - // so earlier pending events are superseded — discard them and process only the latest. - PartitionChangeEvent latest = null; + // A PartitionChangeEvent carries only the queue keys whose partitions changed (an empty set for a removed key), + // not a full snapshot: merge the pending events per queue key, the latest partitions of each key win. + Map> latestPartitions = new HashMap<>(); PartitionChangeEvent event; while ((event = pendingEvents.poll()) != null) { - latest = event; + latestPartitions.putAll(event.getNewPartitions()); } - if (latest == null) { + if (latestPartitions.isEmpty()) { return; } try { - processPartitionChangeEvent(latest); + processPartitionChanges(latestPartitions); } catch (Throwable t) { - log.error("Failed to handle partition change event: {}", latest, t); + log.error("Failed to handle partition changes: {}", latestPartitions, t); } } - private void processPartitionChangeEvent(PartitionChangeEvent event) { - event.getNewPartitions().forEach(((queueKey, partitions) -> { + private void processPartitionChanges(Map> newPartitions) { + newPartitions.forEach(((queueKey, partitions) -> { IntegrationType type = IntegrationType.valueOf(queueKey.getQueueName()); subscribeEventsMap.computeIfAbsent(type, t -> new ConcurrentLinkedQueue<>()).add(partitions); queueExecutor.submit(() -> refreshIntegrationsByType(type)); @@ -199,7 +201,7 @@ public class DefaultClusterIntegrationService extends TbApplicationEventListener } finally { // Mark as started and drain pending events even on failure, so that partition change events are not stuck in the queue forever. // After started=true, any new events will drain themselves in onTbApplicationEvent(). - // drainPendingEvents() is synchronized, so snapshots are applied in the order they were queued. + // drainPendingEvents() is synchronized, so partition changes are applied in the order they were queued. started = true; drainPendingEvents(); } diff --git a/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java b/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java index 08bd8ad234..112971e221 100644 --- a/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java +++ b/common/integration/cluster-integration-api/src/test/java/org/thingsboard/server/service/integration/DefaultClusterIntegrationServiceTest.java @@ -36,6 +36,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -56,16 +57,19 @@ class DefaultClusterIntegrationServiceTest { private IntegrationManagerService integrationManagerService; @Mock private TbQueueConsumer> mqttConsumer; + @Mock + private TbQueueConsumer> httpConsumer; private DefaultClusterIntegrationService service; @BeforeEach @SuppressWarnings("unchecked") void setUp() { - when(serviceInfoProvider.getSupportedIntegrationTypes()).thenReturn(List.of(IntegrationType.MQTT)); + when(serviceInfoProvider.getSupportedIntegrationTypes()).thenReturn(List.of(IntegrationType.MQTT, IntegrationType.HTTP)); when(queueFactory.createToIntegrationExecutorNotificationsMsgConsumer()) .thenReturn(mock(TbQueueConsumer.class)); when(queueFactory.createToIntegrationExecutorDownlinkMsgConsumer(IntegrationType.MQTT)).thenReturn(mqttConsumer); + when(queueFactory.createToIntegrationExecutorDownlinkMsgConsumer(IntegrationType.HTTP)).thenReturn(httpConsumer); service = new DefaultClusterIntegrationService(serviceInfoProvider, settings, queueFactory, integrationManagerService) { @Override protected void launchMainConsumers() { @@ -128,10 +132,29 @@ class DefaultClusterIntegrationServiceTest { verify(integrationManagerService, timeout(TIMEOUT_MS)).refresh(eq(IntegrationType.MQTT), eq(Collections.emptySet())); } + @Test + void givenEventsForDifferentTypesPendingAtStartup_whenStarted_thenEveryTypeGetsItsLatestPartitions() { + // An event carries only the queue keys whose partitions changed: a later MQTT-only event must not hide HTTP. + service.onApplicationEvent(partitionChangeEvent(Map.of(IntegrationType.MQTT, tpis(0), IntegrationType.HTTP, tpis(1)))); + service.onApplicationEvent(partitionChangeEvent(Map.of(IntegrationType.MQTT, tpis(2)))); + service.onApplicationEvent((ApplicationReadyEvent) null); + + verify(integrationManagerService, timeout(TIMEOUT_MS)).refresh(IntegrationType.HTTP, tpis(1)); + verify(httpConsumer, timeout(TIMEOUT_MS)).subscribe(tpis(1)); + verify(integrationManagerService, timeout(TIMEOUT_MS)).refresh(IntegrationType.MQTT, tpis(2)); + verify(mqttConsumer, timeout(TIMEOUT_MS)).subscribe(tpis(2)); + verify(integrationManagerService, never()).refresh(IntegrationType.MQTT, tpis(0)); + } + private static PartitionChangeEvent partitionChangeEvent(Integer... partitions) { - QueueKey queueKey = new QueueKey(ServiceType.TB_INTEGRATION_EXECUTOR, IntegrationType.MQTT.name()); + return partitionChangeEvent(Map.of(IntegrationType.MQTT, tpis(partitions))); + } + + private static PartitionChangeEvent partitionChangeEvent(Map> partitionsByType) { + Map> newPartitions = partitionsByType.entrySet().stream().collect(Collectors.toMap( + e -> new QueueKey(ServiceType.TB_INTEGRATION_EXECUTOR, e.getKey().name()), Map.Entry::getValue)); return new PartitionChangeEvent(DefaultClusterIntegrationServiceTest.class, ServiceType.TB_INTEGRATION_EXECUTOR, - Map.of(queueKey, tpis(partitions)), Collections.emptyMap()); + newPartitions, Collections.emptyMap()); } private static Set tpis(Integer... partitions) {