This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new bfddafd9ceb9 CAMEL-27900: camel-salesforce: retry a rejected streaming 
subscription on the next successful connect (#31181)
bfddafd9ceb9 is described below

commit bfddafd9ceb9702ea8fcf3a1965dcaa1408baa41
Author: James Netherton <[email protected]>
AuthorDate: Tue Dec 1 17:44:34 2026 +0000

    CAMEL-27900: camel-salesforce: retry a rejected streaming subscription on 
the next successful connect (#31181)
    
    CAMEL-23391 stopped re-adding a channel to channelsToSubscribe, so a 
channel whose subscription the server rejected was never subscribed again after 
the connection recovered. Re-queue the channel when the subscription is given 
up (unless the channel is invalid), so the next successful /meta/connect 
retries it. Only a rejected subscription is re-queued, so the duplicate 
delivery fixed by CAMEL-23391 does not come back.
    
    CometD sends /meta/subscribe only for the first listener of a channel, and 
a rejection removes only that listener. On a retry, remove the leftover 
listeners and subscribe again in one client.batch(), so the /meta/unsubscribe 
and /meta/subscribe go in one request, in order. This covers the 
temporary-error and replayId retries and the retry on connect. subscribe() no 
longer adds a listener the channel already has.
    
    The subscription failure test moves from SubscriptionHelperManualIT (manual 
profile only) to SubscriptionHelperSubscriptionFailureTest, which runs against 
the stub server in the regular build.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../internal/streaming/SubscriptionHelper.java     |  60 ++++-
 .../salesforce/internal/streaming/StubServer.java  |  41 +--
 .../streaming/SubscriptionHelperManualIT.java      |  57 -----
 .../SubscriptionHelperSubscriptionFailureTest.java | 283 +++++++++++++++++++++
 4 files changed, 358 insertions(+), 83 deletions(-)

diff --git 
a/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelper.java
 
b/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelper.java
index 1e842fbe80aa..64aa3d342094 100644
--- 
a/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelper.java
+++ 
b/components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelper.java
@@ -239,10 +239,8 @@ public class SubscriptionHelper extends ServiceSupport {
                                 if (toSubscribe != null) {
                                     LOG.info("Subscribing to channels: {}", 
toSubscribe);
                                     for (var channelName : toSubscribe) {
-                                        var consumers = 
channelToConsumers.getOrDefault(channelName, emptySet());
-                                        for (var consumer : consumers) {
-                                            subscribe(consumer);
-                                        }
+                                        resubscribe(channelName,
+                                                
channelToConsumers.getOrDefault(channelName, emptySet()));
                                     }
                                 }
                             }
@@ -346,6 +344,7 @@ public class SubscriptionHelper extends ServiceSupport {
                 "Error subscribing to %s: %s",
                 firstConsumer.getTopicName(), failure != null ? 
failure.getMessage() : error);
         boolean abort = true;
+        boolean retryOnConnect = true;
 
         LOG.warn(msg);
         if (isTemporaryError(message) || error.equals(AUTHENTICATION_INVALID) 
|| error.startsWith(DENIED_BY_SEC_POLICY)
@@ -373,9 +372,7 @@ public class SubscriptionHelper extends ServiceSupport {
                         .build()
                         .run(component.getCamelContext(), () -> true);
 
-                for (var consumer : consumers) {
-                    subscribe(consumer);
-                }
+                resubscribe(channelName, consumers);
             }
         } else if (error.matches(INVALID_REPLAY_ID_PATTERN)) {
             abort = false;
@@ -383,21 +380,59 @@ public class SubscriptionHelper extends ServiceSupport {
             LOG.warn(error);
             LOG.warn("Falling back to replayId {} for channel {}", 
fallBackReplayId, channelName);
             replayExtension.setReplayId(channelName, fallBackReplayId);
-            for (var consumer : consumers) {
-                subscribe(consumer);
-            }
+            resubscribe(channelName, consumers);
         } else if (error.matches(CHANNEL_INVALID_PATTERN)) {
             LOG.warn("Channel invalid for channel {}, removing from 
subscription list", channelName);
             channelsToSubscribe.remove(channelName);
+            retryOnConnect = false;
         }
 
         if (abort && client != null) {
+            if (retryOnConnect) {
+                // the server rejected the subscription, so retry it on the 
next successful connect
+                requeueChannel(channelName);
+            }
             for (var consumer : consumers) {
                 consumer.getExceptionHandler().handleException(msg, new 
SalesforceException(msg, failure));
             }
         }
     }
 
+    /**
+     * CometD sends /meta/subscribe only for the first listener of a channel, 
and a rejection removes only that
+     * listener. Remove the listeners left on the channel before subscribing 
again, so that the subscribe is sent to the
+     * server. Both go in one batch: one request, so the server cannot handle 
the unsubscribe after the subscribe.
+     */
+    private void resubscribe(String channelName, Set<StreamingApiConsumer> 
consumers) {
+        lock.lock();
+        try {
+            if (client == null) {
+                return;
+            }
+            final ClientSessionChannel clientChannel = 
client.getChannel(channelName);
+            client.batch(() -> {
+                for (var consumer : consumers) {
+                    var listener = consumerToListener.get(consumer);
+                    if (listener != null) {
+                        clientChannel.unsubscribe(listener);
+                    }
+                }
+                for (var consumer : consumers) {
+                    subscribe(consumer);
+                }
+            });
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    private void requeueChannel(String channelName) {
+        // best effort: a channel left behind by a concurrent unsubscribe has 
no consumers, so connect skips it
+        if (channelToConsumers.containsKey(channelName)) {
+            channelsToSubscribe.add(channelName);
+        }
+    }
+
     @Override
     protected void doStart() throws Exception {
         session = component.getSession();
@@ -602,6 +637,11 @@ public class SubscriptionHelper extends ServiceSupport {
 
             // subscribe asynchronously
             final ClientSessionChannel clientChannel = 
client.getChannel(channelName);
+            // CometD keeps the listeners in a list, the same listener added 
twice would get every event twice
+            if (clientChannel.getSubscribers().contains(messageListener)) {
+                LOG.debug("Consumer already subscribed to channel {}", 
channelName);
+                return;
+            }
             clientChannel.subscribe(messageListener);
         } finally {
             lock.unlock();
diff --git 
a/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/StubServer.java
 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/StubServer.java
index 1962cdf7b434..1a075cf0bd89 100644
--- 
a/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/StubServer.java
+++ 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/StubServer.java
@@ -25,6 +25,8 @@ import java.util.Objects;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Predicate;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import jakarta.servlet.http.HttpServletResponse;
 
@@ -43,6 +45,8 @@ class StubServer {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(StubServer.class);
 
+    private static final Pattern MESSAGE_ID = 
Pattern.compile("\"id\":\"(\\d+)\"");
+
     private final List<StubResponse> defaultStubs = new ArrayList<>();
 
     private final Server server;
@@ -91,9 +95,7 @@ class StubServer {
             response.setStatus(stub.responseStatus);
             response.getHeaders().add("Content-Type", 
"application/json;charset=UTF-8");
 
-            final String id = messageIdFrom(body.toString());
-
-            stub.writeTo(id, response, callback);
+            stub.writeTo(messageIdsFrom(body.toString()), response, callback);
 
             callback.succeeded();
             return true;
@@ -176,10 +178,11 @@ class StubServer {
             return requestCondition.test(body);
         }
 
-        private void writeTo(final String messageId, final Response out, final 
Callback callback) throws IOException {
+        private void writeTo(final List<String> messageIds, final Response 
out, final Callback callback)
+                throws IOException {
             if (responseString != null) {
                 out.write(true,
-                        ByteBuffer.wrap(responseString.replace("$id", 
messageId).getBytes(StandardCharsets.UTF_8)),
+                        ByteBuffer.wrap(withIds(responseString, 
messageIds).getBytes(StandardCharsets.UTF_8)),
                         callback);
                 return;
             }
@@ -190,7 +193,7 @@ class StubServer {
                         final String message = responseMessages.poll(25, 
TimeUnit.MILLISECONDS);
                         if (message != null) {
                             out.write(true,
-                                    ByteBuffer.wrap(message.replace("$id", 
messageId).getBytes(StandardCharsets.UTF_8)),
+                                    ByteBuffer.wrap(withIds(message, 
messageIds).getBytes(StandardCharsets.UTF_8)),
                                     callback);
                             return;
                         }
@@ -286,18 +289,24 @@ class StubServer {
         return connector;
     }
 
-    private static String messageIdFrom(final String body) {
-        int idx = body.indexOf("\"id\":\"");
-        String id = "";
+    private static List<String> messageIdsFrom(final String body) {
+        final List<String> ids = new ArrayList<>();
+        final Matcher matcher = MESSAGE_ID.matcher(body);
+        while (matcher.find()) {
+            ids.add(matcher.group(1));
+        }
+        return ids;
+    }
 
-        if (idx > 0) {
-            idx += 6;
-            char ch;
-            while (Character.isDigit(ch = body.charAt(idx++))) {
-                id += ch;
-            }
+    /**
+     * $id is the id of the first message of the request, $id2, $id3... the 
ids of the next messages of a batch.
+     */
+    private static String withIds(final String response, final List<String> 
messageIds) {
+        String result = response;
+        for (int i = messageIds.size(); i >= 2; i--) {
+            result = result.replace("$id" + i, messageIds.get(i - 1));
         }
-        return id;
+        return result.replace("$id", messageIds.isEmpty() ? "" : 
messageIds.get(0));
     }
 
 }
diff --git 
a/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperManualIT.java
 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperManualIT.java
index 2e73104a4a68..2641101946a1 100644
--- 
a/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperManualIT.java
+++ 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperManualIT.java
@@ -45,8 +45,6 @@ import org.slf4j.LoggerFactory;
 import static java.util.concurrent.TimeUnit.SECONDS;
 import static 
org.apache.camel.component.salesforce.internal.streaming.SubscriptionHelperManualIT.MessageArgumentMatcher.messageWithName;
 import static org.awaitility.Awaitility.await;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.hasSize;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.argThat;
 import static org.mockito.Mockito.atLeastOnce;
@@ -351,61 +349,6 @@ public class SubscriptionHelperManualIT {
         verifyNoMoreInteractions(consumer);
     }
 
-    @Test
-    void shouldResubscribeOnSubscriptionFailure() {
-        var consumer = createConsumer("Contact");
-        var subscribeAttempts = new AtomicInteger(0);
-        subscription.client.getChannel("/meta/subscribe").addListener(
-                (MessageListener) (clientSessionChannel, message) -> {
-                    var subscription = (String) message.get("subscription");
-                    if (subscription != null && 
subscription.contains("Contact")) {
-                        subscribeAttempts.incrementAndGet();
-                    }
-                });
-
-        server.reset();
-        server.replyTo("POST", "/cometd/" + 
SalesforceEndpointConfig.DEFAULT_VERSION + "/subscribe",
-                s -> s.contains("/topic/Contact"),
-                """
-                        [
-                          {
-                            "clientId": "5ra4927ikfky6cb12juthkpofeu8aaa",
-                            "channel": "/meta/subscribe",
-                            "id": "$id",
-                            "subscription": "/topic/Contact",
-                            "successful": false
-                          }
-                        ]""");
-        subscription.subscribe(consumer);
-        await().atMost(10, SECONDS).until(() -> subscribeAttempts.get() == 1);
-        
assertThat(subscription.client.getChannel("/topic/Contact").getSubscribers(), 
hasSize(0));
-
-        server.reset();
-        server.replyTo("POST", "/cometd/" + 
SalesforceEndpointConfig.DEFAULT_VERSION + "/subscribe",
-                s -> s.contains("/topic/Contact"),
-                """
-                        [
-                          {
-                            "clientId": "5ra4927ikfky6cb12juthkpofeu8bbb",
-                            "channel": "/meta/subscribe",
-                            "id": "$id",
-                            "subscription": "/topic/Contact",
-                            "successful": true
-                          }
-                        ]""");
-        messages.add("""
-                [
-                  {
-                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
-                    "channel": "/meta/connect",
-                    "id": "$id",
-                    "successful": true
-                  }
-                ]""");
-        await().atMost(10, SECONDS).until(() -> subscribeAttempts.get() == 2);
-        
assertThat(subscription.client.getChannel("/topic/Contact").getSubscribers(), 
hasSize(1));
-    }
-
     @Test
     void shouldResubscribeOnHelperRestart() {
         var consumer = createConsumer("Person");
diff --git 
a/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperSubscriptionFailureTest.java
 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperSubscriptionFailureTest.java
new file mode 100644
index 000000000000..2f8641e010f0
--- /dev/null
+++ 
b/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/internal/streaming/SubscriptionHelperSubscriptionFailureTest.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.camel.component.salesforce.internal.streaming;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.salesforce.AuthenticationType;
+import org.apache.camel.component.salesforce.SalesforceComponent;
+import org.apache.camel.component.salesforce.SalesforceEndpoint;
+import org.apache.camel.component.salesforce.SalesforceEndpointConfig;
+import org.apache.camel.component.salesforce.StreamingApiConsumer;
+import org.apache.camel.component.salesforce.api.SalesforceException;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ExceptionHandler;
+import org.cometd.bayeux.client.ClientSessionChannel.MessageListener;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * A subscription that the server rejects is retried on the next successful 
connect. Runs against {@link StubServer}, no
+ * Salesforce org needed.
+ */
+class SubscriptionHelperSubscriptionFailureTest {
+
+    private static final String COMETD = "/cometd/" + 
SalesforceEndpointConfig.DEFAULT_VERSION;
+    private static final String CHANNEL = "/topic/Contact";
+
+    private final SalesforceEndpointConfig config = new 
SalesforceEndpointConfig();
+    private final BlockingQueue<String> connectReplies = new 
LinkedBlockingDeque<>();
+    private final AtomicInteger subscribeReplies = new AtomicInteger();
+
+    private StubServer server;
+    private CamelContext camel;
+    private SalesforceComponent salesforce;
+    private SubscriptionHelper subscription;
+
+    @BeforeEach
+    void start() throws Exception {
+        server = new StubServer();
+        final String instanceUrl = "http://localhost:"; + server.port();
+        server.replyTo("POST", "/services/oauth2/token", """
+                {
+                  "instance_url": "%s",
+                  "access_token": "00D4100000xxxxx!faketoken",
+                  "id": 
"https://login.salesforce.com/id/00D4100000xxxxxxxx/0054100000xxxxxxxx";
+                }""".formatted(instanceUrl));
+        server.replyTo("GET", "/services/oauth2/revoke", 200);
+        server.replyTo("POST", COMETD + "/handshake", """
+                [
+                  {
+                    "ext": {"replay": true, "payload.format": true},
+                    "minimumVersion": "1.0",
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "supportedConnectionTypes": ["long-polling"],
+                    "channel": "/meta/handshake",
+                    "id": "$id",
+                    "version": "1.0",
+                    "successful": true
+                  }
+                ]""");
+        server.replyTo("POST", COMETD + "/connect", req -> 
req.contains("\"timeout\":0"), """
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "advice": {"interval": 0, "timeout": 110000, "reconnect": 
"retry"},
+                    "channel": "/meta/connect",
+                    "id": "$id",
+                    "successful": true
+                  }
+                ]""");
+        server.replyTo("POST", COMETD + "/connect", connectReplies);
+        server.replyTo("POST", COMETD + "/unsubscribe", """
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/unsubscribe",
+                    "id": "$id",
+                    "subscription": "%s",
+                    "successful": true
+                  }
+                ]""".formatted(CHANNEL));
+        server.replyTo("POST", COMETD + "/disconnect", """
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/disconnect",
+                    "id": "$id",
+                    "successful": true
+                  }
+                ]""");
+        server.stubsAsDefaults();
+
+        camel = new DefaultCamelContext();
+        camel.start();
+        salesforce = new SalesforceComponent(camel);
+        salesforce.setLoginUrl(instanceUrl);
+        salesforce.setClientId("clientId");
+        salesforce.setClientSecret("clientSecret");
+        salesforce.setRefreshToken("refreshToken");
+        salesforce.setAuthenticationType(AuthenticationType.REFRESH_TOKEN);
+        salesforce.setConfig(config);
+        salesforce.start();
+        subscription = new SubscriptionHelper(salesforce);
+        subscription.start();
+
+        
subscription.client.getChannel("/meta/subscribe").addListener((MessageListener) 
(channel, message) -> {
+            if (CHANNEL.equals(message.get("subscription"))) {
+                subscribeReplies.incrementAndGet();
+            }
+        });
+    }
+
+    @AfterEach
+    void stop() {
+        if (subscription != null) {
+            subscription.stop();
+        }
+        if (salesforce != null) {
+            salesforce.stop();
+        }
+        if (camel != null) {
+            camel.stop();
+        }
+        if (server != null) {
+            server.stop();
+        }
+    }
+
+    @Test
+    void shouldResubscribeOnConnectAfterSubscriptionFailure() {
+        var handler = mock(ExceptionHandler.class);
+        var consumer = createConsumer(handler);
+
+        replyToSubscribe(false);
+        subscription.subscribe(consumer);
+        verify(handler, timeout(10000)).handleException(anyString(), 
any(SalesforceException.class));
+        
assertThat(subscription.client.getChannel(CHANNEL).getSubscribers()).isEmpty();
+
+        replyToSubscribe(true);
+        connectSuccessfully();
+
+        // subscribe() adds the listener before the request is sent, so wait 
for the reply
+        await().atMost(10, SECONDS).until(() -> subscribeReplies.get() >= 2);
+        assertThat(subscribeReplies).hasValue(2);
+        
assertThat(subscription.client.getChannel(CHANNEL).getSubscribers()).hasSize(1);
+    }
+
+    @Test
+    void shouldResubscribeAllConsumersOfChannelAfterSubscriptionFailure() {
+        var handlerA = mock(ExceptionHandler.class);
+        var handlerB = mock(ExceptionHandler.class);
+        var consumerA = createConsumer(handlerA);
+        var consumerB = createConsumer(handlerB);
+
+        // only the first subscribe of a channel goes to the server, the 
second one is local to the client
+        var rejections = new LinkedBlockingDeque<String>();
+        server.reset();
+        server.replyTo("POST", COMETD + "/subscribe", req -> 
req.contains(CHANNEL), rejections);
+        subscription.subscribe(consumerA);
+        subscription.subscribe(consumerB);
+        // reject only once B is subscribed too, otherwise B's subscribe goes 
to the server as well
+        rejections.add(subscribeReply(false));
+        verify(handlerA, timeout(10000)).handleException(anyString(), 
any(SalesforceException.class));
+        verify(handlerB, timeout(10000)).handleException(anyString(), 
any(SalesforceException.class));
+        // the rejection removes only consumer A's listener, the retry 
unsubscribes B and subscribes again in one batch
+        
assertThat(subscription.client.getChannel(CHANNEL).getSubscribers()).hasSize(1);
+
+        replyToSubscribe(true);
+        var batches = new LinkedBlockingDeque<String>();
+        // records each batched request, and matches all of them
+        server.replyTo("POST", COMETD, req -> batches.add(req), """
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/unsubscribe",
+                    "id": "$id",
+                    "subscription": "%1$s",
+                    "successful": true
+                  },
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/subscribe",
+                    "id": "$id2",
+                    "subscription": "%1$s",
+                    "successful": true
+                  }
+                ]""".formatted(CHANNEL));
+        connectSuccessfully();
+
+        // subscribe() adds the listeners before the request is sent, so wait 
for the reply
+        await().atMost(10, SECONDS).until(() -> subscribeReplies.get() >= 2);
+        assertThat(subscribeReplies).hasValue(2);
+        
assertThat(subscription.client.getChannel(CHANNEL).getSubscribers()).hasSize(2);
+        assertThat(batches).singleElement().satisfies(batch -> {
+            assertThat(batch).contains("/meta/unsubscribe", "/meta/subscribe");
+            
assertThat(batch.indexOf("/meta/unsubscribe")).isLessThan(batch.indexOf("/meta/subscribe"));
+        });
+    }
+
+    @Test
+    void shouldNotAddListenerTwiceWhenConsumerSubscribesAgain() {
+        var consumer = createConsumer(mock(ExceptionHandler.class));
+
+        replyToSubscribe(true);
+        subscription.subscribe(consumer);
+        await().atMost(10, SECONDS).until(() -> subscribeReplies.get() == 1);
+
+        subscription.subscribe(consumer);
+
+        
assertThat(subscription.client.getChannel(CHANNEL).getSubscribers()).hasSize(1);
+    }
+
+    private StreamingApiConsumer createConsumer(ExceptionHandler handler) {
+        var endpoint = mock(SalesforceEndpoint.class);
+        when(endpoint.getConfiguration()).thenReturn(config);
+        when(endpoint.getComponent()).thenReturn(salesforce);
+        when(endpoint.getTopicName()).thenReturn("Contact");
+
+        var consumer = mock(StreamingApiConsumer.class);
+        when(consumer.getTopicName()).thenReturn("Contact");
+        when(consumer.getEndpoint()).thenReturn(endpoint);
+        when(consumer.getExceptionHandler()).thenReturn(handler);
+        return consumer;
+    }
+
+    private void replyToSubscribe(boolean successful) {
+        server.reset();
+        server.replyTo("POST", COMETD + "/subscribe", req -> 
req.contains(CHANNEL), subscribeReply(successful));
+    }
+
+    private static String subscribeReply(boolean successful) {
+        return """
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/subscribe",
+                    "id": "$id",
+                    "subscription": "%s",
+                    "successful": %s
+                  }
+                ]""".formatted(CHANNEL, successful);
+    }
+
+    private void connectSuccessfully() {
+        connectReplies.add("""
+                [
+                  {
+                    "clientId": "5ra4927ikfky6cb12juthkpofeu8",
+                    "channel": "/meta/connect",
+                    "id": "$id",
+                    "successful": true
+                  }
+                ]""");
+    }
+}

Reply via email to