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 ab0f82c34792 CAMEL-26955: camel-google-pubsub - a DST fake world for 
the synchronous pull consumer (#29996)
ab0f82c34792 is described below

commit ab0f82c347929b24c691c849bb2ac8e854418e87
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 15 14:16:13 2026 +0530

    CAMEL-26955: camel-google-pubsub - a DST fake world for the synchronous 
pull consumer (#29996)
    
    A deterministic simulation test (camel-test-dst) of the camel-google-pubsub 
consumer with synchronousPull=true, in the same form as the SQS world: 
PubsubConsumerDstTest (1000 seeds), PubsubWorld and FakePubsub. Test only; no 
main code changes.
    
    The real consumer and Camel's routing run on the virtual-time loop; only 
the subscription is faked behind the SubscriberStub, written from the Pub/Sub 
documentation of Pull, Acknowledge and ModifyAckDeadline. The seed picks the 
ack mode, ack deadline, maxMessagesPerPoll, maxDeliveryAttempts and fault 
rates, and injects failed pulls, acks and nacks, slow answers, failed or slow 
processing, route restarts and a stop and start of the same consumer. The world 
is checked against CAMEL-2664 [...]
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/components/google-pubsub.json    |   3 +
 .../org/apache/camel/catalog/docs/test-dst.adoc    |  10 +
 .../camel-google/camel-google-pubsub/pom.xml       |  27 +-
 .../component/google/pubsub/google-pubsub.json     |   3 +
 .../component/google/pubsub/dst/FakePubsub.java    | 487 ++++++++++++++++++++
 .../google/pubsub/dst/PubsubConsumerDstTest.java   |  38 ++
 .../component/google/pubsub/dst/PubsubWorld.java   | 503 +++++++++++++++++++++
 .../src/test/resources/log4j2.properties           |   9 +-
 .../camel-test-dst/src/main/docs/test-dst.adoc     |  10 +
 9 files changed, 1088 insertions(+), 2 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/google-pubsub.json
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/google-pubsub.json
index 685ef7d0d48c..e573a8940f94 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/google-pubsub.json
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/google-pubsub.json
@@ -72,5 +72,8 @@
     "loggerId": { "index": 18, "kind": "parameter", "displayName": "Logger 
Id", "group": "advanced", "label": "advanced", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": true, "autowired": 
false, "secret": false, "description": "To use a custom logger name" },
     "authenticate": { "index": 19, "kind": "parameter", "displayName": 
"Authenticate", "group": "security", "label": "security", "required": false, 
"type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": 
false, "secret": false, "defaultValue": true, "description": "Use Credentials 
when interacting with PubSub service (no authentication is required when using 
emulator)." },
     "serviceAccountKey": { "index": 20, "kind": "parameter", "displayName": 
"Service Account Key", "group": "security", "label": "security", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "The Service account key 
that can be used as credentials for the PubSub publisher\/subscriber. It can be 
loaded by default from classpath, but you can prefix with classpath:, file:, or 
http: to load the resour [...]
+  },
+  "dstWorlds": {
+    "PubsubWorld": { "javaType": 
"org.apache.camel.component.google.pubsub.dst.PubsubWorld", "fake": 
"FakePubsub: a subscription (Pull, Acknowledge, ModifyAckDeadline, ack 
deadlines, dead letter policy) behind the SubscriberStub of synchronousPull", 
"covers": [ "synchronousPull with ackMode AUTO, and ackMode NONE with grouped 
messages acked or nacked together", "ack deadlines that expire while a message 
is processed", "the max delivery attempts of a subscription with a dead letter 
policy [...]
   }
 }
diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
index 549386f731d8..ffdc45e6d8a6 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
@@ -81,6 +81,16 @@ a|* checkpointing by checkpointBatchSize and 
checkpointBatchTimeout
 * an asynchronous downstream step
 |CAMEL-25683, CAMEL-25738, CAMEL-25781
 
+|camel-google-pubsub
+|`PubsubWorld` (`PubsubConsumerDstTest`)
+|FakePubsub: a subscription (Pull, Acknowledge, ModifyAckDeadline, ack 
deadlines, dead letter policy) behind the SubscriberStub of synchronousPull
+a|* synchronousPull with ackMode AUTO, and ackMode NONE with grouped messages 
acked or nacked together
+* ack deadlines that expire while a message is processed
+* the max delivery attempts of a subscription with a dead letter policy
+* route stop and start while the consumer pulls
+* a stop and start of the same consumer in one step, as a throttling route 
policy does
+|CAMEL-25712, CAMEL-25790, CAMEL-26647
+
 |camel-kafka-share
 |`KafkaShareWorld` (`KafkaShareConsumerDstTest`)
 |FakeShareGroup: a share group (KIP-932) of one topic with one partition, 
behind ShareConsumer
diff --git a/components/camel-google/camel-google-pubsub/pom.xml 
b/components/camel-google/camel-google-pubsub/pom.xml
index 4161b879cac7..dbc7ebc3f83c 100644
--- a/components/camel-google/camel-google-pubsub/pom.xml
+++ b/components/camel-google/camel-google-pubsub/pom.xml
@@ -43,7 +43,8 @@
         <skipITs.s390x>true</skipITs.s390x>
         <skipTests.s390x>true</skipTests.s390x>
         <!-- Make use of native access during unit and IT test execution only 
-->
-        
<camel.surefire.fork.additional-vmargs>--enable-native-access=ALL-UNNAMED</camel.surefire.fork.additional-vmargs>
+        <!-- the DST tests load the byte code agent of camel-test-dst when the 
JVM starts (see test-dst.adoc) -->
+        
<camel.surefire.fork.additional-vmargs>--enable-native-access=ALL-UNNAMED 
"-javaagent:${net.bytebuddy:byte-buddy-agent:jar}"</camel.surefire.fork.additional-vmargs>
         
<camel.failsafe.fork.additional-vmargs>--enable-native-access=ALL-UNNAMED</camel.failsafe.fork.additional-vmargs>
     </properties>
 
@@ -93,5 +94,29 @@
             <artifactId>assertj-core</artifactId>
             <scope>test</scope>
         </dependency>
+        <!-- deterministic simulation test of the synchronous pull consumer 
(dst package) -->
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-test-dst</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <!-- sets the property net.bytebuddy:byte-buddy-agent:jar to 
the path of the agent of the DST tests -->
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-dependency-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>dst-agent-path</id>
+                        <goals>
+                            <goal>properties</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
 </project>
diff --git 
a/components/camel-google/camel-google-pubsub/src/generated/resources/META-INF/org/apache/camel/component/google/pubsub/google-pubsub.json
 
b/components/camel-google/camel-google-pubsub/src/generated/resources/META-INF/org/apache/camel/component/google/pubsub/google-pubsub.json
index 685ef7d0d48c..e573a8940f94 100644
--- 
a/components/camel-google/camel-google-pubsub/src/generated/resources/META-INF/org/apache/camel/component/google/pubsub/google-pubsub.json
+++ 
b/components/camel-google/camel-google-pubsub/src/generated/resources/META-INF/org/apache/camel/component/google/pubsub/google-pubsub.json
@@ -72,5 +72,8 @@
     "loggerId": { "index": 18, "kind": "parameter", "displayName": "Logger 
Id", "group": "advanced", "label": "advanced", "required": false, "type": 
"string", "javaType": "java.lang.String", "deprecated": true, "autowired": 
false, "secret": false, "description": "To use a custom logger name" },
     "authenticate": { "index": 19, "kind": "parameter", "displayName": 
"Authenticate", "group": "security", "label": "security", "required": false, 
"type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": 
false, "secret": false, "defaultValue": true, "description": "Use Credentials 
when interacting with PubSub service (no authentication is required when using 
emulator)." },
     "serviceAccountKey": { "index": 20, "kind": "parameter", "displayName": 
"Service Account Key", "group": "security", "label": "security", "required": 
false, "type": "string", "javaType": "java.lang.String", "deprecated": false, 
"autowired": false, "secret": false, "description": "The Service account key 
that can be used as credentials for the PubSub publisher\/subscriber. It can be 
loaded by default from classpath, but you can prefix with classpath:, file:, or 
http: to load the resour [...]
+  },
+  "dstWorlds": {
+    "PubsubWorld": { "javaType": 
"org.apache.camel.component.google.pubsub.dst.PubsubWorld", "fake": 
"FakePubsub: a subscription (Pull, Acknowledge, ModifyAckDeadline, ack 
deadlines, dead letter policy) behind the SubscriberStub of synchronousPull", 
"covers": [ "synchronousPull with ackMode AUTO, and ackMode NONE with grouped 
messages acked or nacked together", "ack deadlines that expire while a message 
is processed", "the max delivery attempts of a subscription with a dead letter 
policy [...]
   }
 }
diff --git 
a/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/FakePubsub.java
 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/FakePubsub.java
new file mode 100644
index 000000000000..81183ed0aafe
--- /dev/null
+++ 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/FakePubsub.java
@@ -0,0 +1,487 @@
+/*
+ * 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.google.pubsub.dst;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
+
+import com.google.api.core.ApiFuture;
+import com.google.api.gax.rpc.ApiCallContext;
+import com.google.api.gax.rpc.StatusCode;
+import com.google.api.gax.rpc.UnaryCallable;
+import com.google.api.gax.rpc.UnavailableException;
+import com.google.cloud.pubsub.v1.stub.SubscriberStub;
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Empty;
+import com.google.protobuf.Timestamp;
+import com.google.pubsub.v1.AcknowledgeRequest;
+import com.google.pubsub.v1.ModifyAckDeadlineRequest;
+import com.google.pubsub.v1.PubsubMessage;
+import com.google.pubsub.v1.PullRequest;
+import com.google.pubsub.v1.PullResponse;
+import com.google.pubsub.v1.ReceivedMessage;
+import org.apache.camel.test.dst.Dst;
+import org.apache.camel.test.dst.DstExecutor;
+import org.apache.camel.test.dst.DstLedger;
+
+/**
+ * A fake Google Cloud Pub/Sub subscription behind the {@link SubscriberStub} 
of the synchronous pull, written from the
+ * Pub/Sub documentation, not from the Camel consumer:
+ * <ul>
+ * <li>[P] Pull 
(https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#google.pubsub.v1.Subscriber.Pull):
+ * returns at most max_messages, "The server may return fewer than 
max_messages"; with return_immediately=false it waits
+ * for messages, and may still answer with none. The delivery_attempt of a 
received message is set only when the
+ * subscription has a dead letter policy, and is 1 for the first delivery.</li>
+ * <li>[D] The ack deadline 
(https://cloud.google.com/pubsub/docs/lease-management): a message that is not 
acknowledged
+ * before its deadline is delivered again, with a new ack id.</li>
+ * <li>[A] Acknowledge: "Acknowledging a message whose ack deadline has 
expired may succeed, but such a message may be
+ * redelivered later. Acknowledging a message more than once will not result 
in an error." (Here: an ack of the ack id
+ * of the current delivery takes effect, also after its deadline, as long as 
the message was not delivered again; an ack
+ * of an older ack id does nothing, which is assumed.)</li>
+ * <li>[M] ModifyAckDeadline with ack_deadline_seconds 0: "the message is 
immediately made available for another
+ * delivery".</li>
+ * <li>[L] Dead lettering 
(https://cloud.google.com/pubsub/docs/handling-failures): once a message was 
delivered
+ * max_delivery_attempts times without an acknowledgement, the next nack or 
expired deadline forwards it to the dead
+ * letter topic instead of delivering it again.</li>
+ * <li>[E] A failed call: UNAVAILABLE (retryable), as the client library 
reports it.</li>
+ * </ul>
+ * Not modelled: the streaming pull of the asynchronous subscriber, message 
ordering, exactly-once delivery, filters,
+ * retention and seek, the retry policy delays of the subscription, flow 
control.
+ * <p>
+ * Timing (one-stack rule): a pull returns a future at once (as the gRPC 
client does) that completes after its latency
+ * with the messages available then; acknowledge and modifyAckDeadline take 
effect at the start of their latency.
+ */
+final class FakePubsub {
+
+    static final String PROJECT = "dst-project";
+    static final String SUBSCRIPTION = "dst-subscription";
+
+    enum State {
+        AVAILABLE,
+        OUTSTANDING,
+        ACKED,
+        DEAD
+    }
+
+    static final class Msg {
+        final String id;
+        State state = State.AVAILABLE;
+        int deliveries;
+        String ackId;
+        long deadline;
+
+        Msg(String id) {
+            this.id = id;
+        }
+    }
+
+    private final Dst dst;
+    private final DstLedger ledger;
+    private final DstExecutor server;
+    final Map<String, Msg> messages = new LinkedHashMap<>();
+    private final Map<String, Msg> byAckId = new LinkedHashMap<>();
+    final List<String> violations = new ArrayList<>();
+    int ackDeadlineSeconds = 10;
+    int maxDeliveryAttempts;
+    double pullFailRate;
+    double ackFailRate;
+    boolean faults = true;
+    /** Whether the route is stopped: a pull issued then is a violation (see 
the world). */
+    boolean routeStopped;
+    final List<String> pullsWhileStopped = new ArrayList<>();
+    int pullsInFlight;
+    int maxPullsInFlight;
+    /** Called with the delivery ("id#n") of each ack and nack the 
subscription gets, for the checks of the world. */
+    Consumer<String> onAck = d -> {
+    };
+    Consumer<String> onNack = d -> {
+    };
+    private int calls;
+
+    FakePubsub(Dst dst, DstLedger ledger) {
+        this.dst = dst;
+        this.ledger = ledger;
+        this.server = dst.executor("pubsub", Integer.MAX_VALUE);
+    }
+
+    void publish(String id) {
+        messages.put(id, new Msg(id));
+        ledger.record("published", "s", id);
+    }
+
+    /** [D] [L] deadlines that expired. */
+    void expire() {
+        for (Msg m : messages.values()) {
+            if (m.state == State.OUTSTANDING && dst.now() >= m.deadline) {
+                ledger.record("deadlineExpired", "s", m.id);
+                release(m, "ack deadline expired");
+            }
+        }
+    }
+
+    private void release(Msg m, String why) {
+        if (maxDeliveryAttempts > 0 && m.deliveries >= maxDeliveryAttempts) {
+            m.state = State.DEAD;
+            ledger.record("deadLettered", "s", m.id);
+        } else {
+            m.state = State.AVAILABLE;
+        }
+        dst.trace("fake: " + m.id + " " + why + " -> " + m.state);
+    }
+
+    boolean available() {
+        expire();
+        return messages.values().stream().anyMatch(m -> m.state == 
State.AVAILABLE);
+    }
+
+    boolean settled() {
+        expire();
+        return messages.values().stream().allMatch(m -> m.state == State.ACKED 
|| m.state == State.DEAD);
+    }
+
+    String stateOf(String id) {
+        Msg m = messages.get(id);
+        return m == null ? "not published" : m.state + "/d" + m.deliveries;
+    }
+
+    String unsettled() {
+        return messages.values().stream().filter(m -> m.state != State.ACKED 
&& m.state != State.DEAD)
+                .map(m -> m.id + "=" + m.state + "/d" + 
m.deliveries).toList().toString();
+    }
+
+    private static StatusCode unavailable() {
+        return new StatusCode() {
+            @Override
+            public Code getCode() {
+                return Code.UNAVAILABLE;
+            }
+
+            @Override
+            public Object getTransportCode() {
+                return "UNAVAILABLE";
+            }
+        };
+    }
+
+    private long latency() {
+        return dst.chance(0.1) ? dst.between(200, 2000) : dst.between(5, 80);
+    }
+
+    /** GooglePubsubComponent.getSubscriberStub: a stub on this subscription. 
*/
+    SubscriberStub newStub() {
+        return new SubscriberStub() {
+            @Override
+            public UnaryCallable<PullRequest, PullResponse> pullCallable() {
+                return new UnaryCallable<>() {
+                    @Override
+                    public ApiFuture<PullResponse> futureCall(PullRequest 
request, ApiCallContext context) {
+                        return pull(request);
+                    }
+                };
+            }
+
+            @Override
+            public UnaryCallable<AcknowledgeRequest, Empty> 
acknowledgeCallable() {
+                return new UnaryCallable<>() {
+                    @Override
+                    public ApiFuture<Empty> futureCall(AcknowledgeRequest 
request, ApiCallContext context) {
+                        throw new UnsupportedOperationException("the consumer 
calls call()");
+                    }
+
+                    @Override
+                    public Empty call(AcknowledgeRequest request) {
+                        acknowledge(request);
+                        return Empty.getDefaultInstance();
+                    }
+                };
+            }
+
+            @Override
+            public UnaryCallable<ModifyAckDeadlineRequest, Empty> 
modifyAckDeadlineCallable() {
+                return new UnaryCallable<>() {
+                    @Override
+                    public ApiFuture<Empty> 
futureCall(ModifyAckDeadlineRequest request, ApiCallContext context) {
+                        throw new UnsupportedOperationException("the consumer 
calls call()");
+                    }
+
+                    @Override
+                    public Empty call(ModifyAckDeadlineRequest request) {
+                        modifyAckDeadline(request);
+                        return Empty.getDefaultInstance();
+                    }
+                };
+            }
+
+            @Override
+            public void close() {
+                // nothing to release
+            }
+
+            @Override
+            public void shutdown() {
+                // nothing to release
+            }
+
+            @Override
+            public boolean isShutdown() {
+                return false;
+            }
+
+            @Override
+            public boolean isTerminated() {
+                return false;
+            }
+
+            @Override
+            public void shutdownNow() {
+                // nothing to release
+            }
+
+            @Override
+            public boolean awaitTermination(long duration, TimeUnit unit) {
+                return true;
+            }
+        };
+    }
+
+    private void checkSubscription(String subscription) {
+        String expected = "projects/" + PROJECT + "/subscriptions/" + 
SUBSCRIPTION;
+        if (!expected.equals(subscription)) {
+            violations.add("a call for the subscription " + subscription);
+        }
+    }
+
+    /** [P] a pull: answered after its latency, or a server wait, with the 
messages available then. */
+    private ApiFuture<PullResponse> pull(PullRequest request) {
+        checkSubscription(request.getSubscription());
+        if (request.getMaxMessages() < 1) {
+            violations.add("pull with max_messages " + 
request.getMaxMessages());
+        }
+        String name = "pull-" + calls++;
+        if (routeStopped) {
+            pullsWhileStopped.add(name + " at t=" + dst.now());
+        }
+        DstFuture<PullResponse> future = new DstFuture<>(name);
+        pullsInFlight++;
+        maxPullsInFlight = Math.max(maxPullsInFlight, pullsInFlight);
+        long serverWait = dst.between(1000, 10_000);
+        long start = dst.now();
+        Runnable[] answer = new Runnable[1];
+        answer[0] = () -> {
+            if (future.isDone()) {
+                return;
+            }
+            if (faults && dst.chance(pullFailRate)) {
+                ledger.record("pullFault", "s", name);
+                pullsInFlight--;
+                future.fail(new ExecutionException(
+                        Dst.injected(
+                                new UnavailableException("dst: pull failed", 
null, unavailable(), true))));
+                return;
+            }
+            if (!available() && dst.now() - start < serverWait) {
+                // [P] the pull waits for messages
+                server.schedule(name + " waits", 1000, answer[0]);
+                return;
+            }
+            pullsInFlight--;
+            future.complete(deliver(request.getMaxMessages(), name));
+        };
+        server.schedule(name, latency(), answer[0]);
+        return future;
+    }
+
+    private PullResponse deliver(int max, String pull) {
+        expire();
+        int budget = max;
+        if (budget > 1 && dst.chance(0.3)) {
+            budget = (int) dst.between(1, budget - 1);
+        }
+        PullResponse.Builder answer = PullResponse.newBuilder();
+        for (Msg m : messages.values()) {
+            if (budget == 0) {
+                break;
+            }
+            if (m.state != State.AVAILABLE) {
+                continue;
+            }
+            m.state = State.OUTSTANDING;
+            m.deliveries++;
+            m.ackId = "ack-" + m.id + "#" + m.deliveries;
+            m.deadline = dst.now() + ackDeadlineSeconds * 1000L;
+            byAckId.put(m.ackId, m);
+            ReceivedMessage.Builder received = 
ReceivedMessage.newBuilder().setAckId(m.ackId)
+                    
.setMessage(PubsubMessage.newBuilder().setMessageId(m.id).setData(ByteString.copyFromUtf8(m.id))
+                            
.setPublishTime(Timestamp.newBuilder().setSeconds((Dst.EPOCH_MILLIS + 
dst.now()) / 1000)));
+            if (maxDeliveryAttempts > 0) {
+                received.setDeliveryAttempt(m.deliveries);
+            }
+            answer.addReceivedMessages(received);
+            ledger.record("delivered", "s", m.id + "#" + m.deliveries);
+            budget--;
+        }
+        if (answer.getReceivedMessagesCount() > 0) {
+            dst.trace("fake: " + pull + " returns " + 
answer.getReceivedMessagesCount() + " messages");
+        }
+        return answer.build();
+    }
+
+    private void acknowledge(AcknowledgeRequest request) {
+        checkSubscription(request.getSubscription());
+        if (request.getAckIdsCount() == 0) {
+            violations.add("acknowledge without ack ids");
+        }
+        if (faults && dst.chance(ackFailRate)) {
+            ledger.record("ackFault", "s", request.getAckIdsList().toString());
+            dst.block(latency(), "acknowledge fails");
+            throw Dst.injected(new UnavailableException("dst: acknowledge 
failed", null, unavailable(), true));
+        }
+        // writes take effect at the start of their latency
+        for (String ackId : request.getAckIdsList()) {
+            Msg m = byAckId.get(ackId);
+            if (m == null) {
+                violations.add("acknowledge of an unknown ack id " + ackId);
+                continue;
+            }
+            onAck.accept(ackId.substring(4));
+            expire();
+            if (ackId.equals(m.ackId) && m.state == State.OUTSTANDING) {
+                m.state = State.ACKED;
+                ledger.record("acked", "s", ackId.substring(4));
+            } else if (ackId.equals(m.ackId) && m.state == State.AVAILABLE && 
dst.chance(0.5)) {
+                // [A] expired, not delivered again yet: the ack may still 
succeed
+                m.state = State.ACKED;
+                ledger.record("acked", "s", ackId.substring(4) + " (after its 
deadline)");
+            } else {
+                ledger.record("ackIgnored", "s", ackId.substring(4));
+            }
+        }
+        dst.block(latency(), "acknowledge");
+    }
+
+    private void modifyAckDeadline(ModifyAckDeadlineRequest request) {
+        checkSubscription(request.getSubscription());
+        if (request.getAckDeadlineSeconds() != 0) {
+            violations.add("modifyAckDeadline to " + 
request.getAckDeadlineSeconds() + " s (only nacks are modelled)");
+        }
+        if (faults && dst.chance(ackFailRate)) {
+            ledger.record("nackFault", "s", 
request.getAckIdsList().toString());
+            dst.block(latency(), "modifyAckDeadline fails");
+            throw Dst.injected(new UnavailableException("dst: 
modifyAckDeadline failed", null, unavailable(), true));
+        }
+        for (String ackId : request.getAckIdsList()) {
+            Msg m = byAckId.get(ackId);
+            if (m == null) {
+                violations.add("modifyAckDeadline of an unknown ack id " + 
ackId);
+                continue;
+            }
+            onNack.accept(ackId.substring(4));
+            expire();
+            if (ackId.equals(m.ackId) && m.state == State.OUTSTANDING) {
+                // [M] [L]
+                ledger.record("nacked", "s", ackId.substring(4));
+                release(m, "nacked");
+            }
+        }
+        dst.block(latency(), "modifyAckDeadline");
+    }
+
+    /**
+     * A future of the run: the consumer waits for it with {@code get()} on 
the loop thread (an ApiFuture is not one of
+     * the futures the harness rewrites), so its wait runs the other tasks of 
the run; a cancel ends the wait.
+     */
+    final class DstFuture<T> implements ApiFuture<T> {
+        private final String name;
+        private T value;
+        private ExecutionException failure;
+        private boolean done;
+        private boolean cancelled;
+
+        DstFuture(String name) {
+            this.name = name;
+        }
+
+        void complete(T value) {
+            if (!done) {
+                this.value = value;
+                done = true;
+            }
+        }
+
+        void fail(ExecutionException failure) {
+            if (!done) {
+                this.failure = failure;
+                done = true;
+            }
+        }
+
+        @Override
+        public void addListener(Runnable listener, Executor executor) {
+            throw new UnsupportedOperationException("not used by the 
synchronous pull");
+        }
+
+        @Override
+        public boolean cancel(boolean mayInterruptIfRunning) {
+            if (done) {
+                return false;
+            }
+            dst.trace("fake: " + name + " cancelled");
+            cancelled = true;
+            done = true;
+            pullsInFlight--;
+            return true;
+        }
+
+        @Override
+        public boolean isCancelled() {
+            return cancelled;
+        }
+
+        @Override
+        public boolean isDone() {
+            return done;
+        }
+
+        @Override
+        public T get() throws ExecutionException {
+            dst.awaitCondition(this::isDone, name);
+            if (cancelled) {
+                throw new CancellationException(name + " cancelled");
+            }
+            if (failure != null) {
+                throw failure;
+            }
+            return value;
+        }
+
+        @Override
+        public T get(long timeout, TimeUnit unit) throws ExecutionException, 
TimeoutException {
+            if (!dst.awaitUntil(this::isDone, unit.toMillis(timeout), name)) {
+                throw new TimeoutException(name);
+            }
+            return get();
+        }
+    }
+}
diff --git 
a/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubConsumerDstTest.java
 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubConsumerDstTest.java
new file mode 100644
index 000000000000..887c63f5e9b9
--- /dev/null
+++ 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubConsumerDstTest.java
@@ -0,0 +1,38 @@
+/*
+ * 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.google.pubsub.dst;
+
+import org.apache.camel.test.dst.Dst;
+import org.apache.camel.test.dst.DstInstrument;
+import org.apache.camel.test.dst.DstTest;
+
+/**
+ * Deterministic simulation test of the camel-google-pubsub consumer 
(synchronousPull) against a fake subscription, with
+ * failed pulls, acknowledgements and nacks, ack deadlines that expire under 
slow processing, the max delivery attempts
+ * of a dead letter policy, grouped messages acked together, and route stops 
while the consumer pulls: a delivery is
+ * acknowledged only after its exchange completed, a stopped consumer does not 
pull, and once the faults cleared every
+ * message is acknowledged or dead lettered. A failing seed is replayed with 
{@code -Ddst.seed=<seed>};
+ * {@code -Ddst.seeds=5000} runs more seeds.
+ */
+@DstInstrument("org.apache.camel.component.google.pubsub")
+class PubsubConsumerDstTest {
+
+    @DstTest(seeds = 1000)
+    void everyDeliveryIsAcknowledgedOnlyAfterItsExchangeCompleted(Dst dst) 
throws Exception {
+        new PubsubWorld(dst).run();
+    }
+}
diff --git 
a/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubWorld.java
 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubWorld.java
new file mode 100644
index 000000000000..47f15e79fa93
--- /dev/null
+++ 
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/dst/PubsubWorld.java
@@ -0,0 +1,503 @@
+/*
+ * 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.google.pubsub.dst;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
+import com.google.cloud.pubsub.v1.stub.SubscriberStub;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.google.pubsub.GooglePubsubComponent;
+import org.apache.camel.component.google.pubsub.GooglePubsubConstants;
+import org.apache.camel.component.google.pubsub.GooglePubsubConsumer;
+import org.apache.camel.component.google.pubsub.GooglePubsubEndpoint;
+import 
org.apache.camel.component.google.pubsub.consumer.GooglePubsubAcknowledge;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.processor.aggregate.GroupedExchangeAggregationStrategy;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.test.dst.Dst;
+import org.apache.camel.test.dst.DstCamel;
+import org.apache.camel.test.dst.DstExecutor;
+import org.apache.camel.test.dst.DstLedger;
+import org.apache.camel.test.dst.DstWorld;
+import org.apache.camel.test.dst.Invariants;
+
+/**
+ * The world around a camel-google-pubsub consumer with synchronousPull=true: 
a fake subscription ({@link FakePubsub}),
+ * a publisher, a route whose processing is sometimes slower than the ack 
deadline and sometimes fails, and an operator
+ * that stops and starts the route. Faults: pulls, acknowledgements and nacks 
fail, answers are slow, deadlines expire.
+ * <p>
+ * The seed picks the ack mode: AUTO (the consumer acks a completed exchange 
and nacks a failed one), or GROUPED
+ * (ackMode=NONE, the route aggregates the messages with 
GroupedExchangeAggregationStrategy and acks or nacks the
+ * aggregated exchange with the GooglePubsubAcknowledge of the header, which 
must ack every grouped message), and the
+ * ack deadline, maxMessagesPerPoll, the dead letter policy of the 
subscription (with maxDeliveryAttempts set on the
+ * endpoint to the same value) and the fault rates.
+ * <p>
+ * concurrentConsumers is 1: a pull loop runs for ever, and with the one-stack 
model a second loop nested above the
+ * first would never let it resume. The operator stops the route only when no 
exchange is in the route and the consumer
+ * has no pending exchange (the shutdown strategy would wait for it for ever 
on the one stack), so a stop happens while
+ * the consumer waits for a pull. A route suspend stops this consumer (it is 
not Suspendable), so it is not driven
+ * apart. With ackMode AUTO the operator also stops and starts the consumer 
itself in one step, as a throttling route
+ * policy does, so that the pull loop of the previous start is still there 
when the consumer runs again. The graceful
+ * shutdown (deferShutdown) cannot be reached between its stop of the pulls 
and the stop of the consumer on the one
+ * stack, so a pull in that window is not driven.
+ * <p>
+ * Properties: a delivery is acknowledged only after its exchange completed, 
and nacked only after it failed or reached
+ * maxDeliveryAttempts (or rejected by the stopped route); a delivery at 
maxDeliveryAttempts is nacked without routing
+ * it; a manual ack of a group acknowledges every message of the group; a 
stopped consumer issues no pull, and the
+ * consumer has at most one pull at a time; once the faults cleared every 
message is acknowledged or dead lettered by
+ * the subscription, and a message published then is routed and acknowledged; 
the consumer uses the subscription as
+ * documented. Messages may be delivered more than once (at-least-once: a 
deadline that expires, a lost
+ * acknowledgement).
+ * <p>
+ * Not explored: ack deadline extensions (synchronousPull does not extend a 
deadline), the asynchronous subscriber
+ * (synchronousPull=false: its lease management and redelivery are inside the 
client library), concurrentConsumers above
+ * 1, message ordering, exactly-once delivery.
+ */
+@DstWorld(component = "google-pubsub",
+          fake = "FakePubsub: a subscription (Pull, Acknowledge, 
ModifyAckDeadline, ack deadlines, dead letter policy)"
+                 + " behind the SubscriberStub of synchronousPull",
+          covers = {
+                  "synchronousPull with ackMode AUTO, and ackMode NONE with 
grouped messages acked or nacked together",
+                  "ack deadlines that expire while a message is processed",
+                  "the max delivery attempts of a subscription with a dead 
letter policy",
+                  "route stop and start while the consumer pulls",
+                  "a stop and start of the same consumer in one step, as a 
throttling route policy does" },
+          faults = {
+                  "Pull fails", "Acknowledge fails", "ModifyAckDeadline (nack) 
fails", "calls answer slowly",
+                  "Pull returns fewer messages than it could", "processing 
fails",
+                  "processing is slower than the ack deadline" },
+          invariants = {
+                  "the consumer uses the subscription as documented",
+                  "a delivery is acknowledged only after its exchange 
completed",
+                  "a delivery is nacked only after its exchange failed or at 
the max delivery attempts",
+                  "a manual ack of a group acknowledges every message of the 
group",
+                  "a stopped consumer issues no pull, and the consumer has one 
pull at a time",
+                  "a delivery at the max delivery attempts is nacked without 
routing it",
+                  "every message is acknowledged or dead lettered once the 
faults cleared",
+                  "a message published once the faults cleared is routed and 
acknowledged" },
+          issues = { "CAMEL-25712", "CAMEL-25790", "CAMEL-26647" })
+final class PubsubWorld {
+
+    static final String ROUTE = "pubsub";
+    /** Published once the faults cleared: a consumer that still pulls routes 
and acknowledges it. */
+    static final String END = "end";
+
+    private final Dst dst;
+    private final DstLedger ledger;
+    private final FakePubsub pubsub;
+    private final boolean grouped;
+    private final int maxMessagesPerPoll;
+    private final double processFailRate;
+    private final List<String> violations = new ArrayList<>();
+    private final List<String> wrongAcks = new ArrayList<>();
+    private final List<String> wrongNacks = new ArrayList<>();
+    private final List<String> groupAcks = new ArrayList<>();
+    private final Set<String> completed = new HashSet<>();
+    private final Set<String> failed = new HashSet<>();
+    private final Set<String> acked = new HashSet<>();
+    private final Set<String> routed = new HashSet<>();
+    private final List<String> routedAtMax = new ArrayList<>();
+    private DefaultCamelContext context;
+    private boolean faults = true;
+    private int sendsLeft;
+    private int opsLeft;
+    private int inRoute;
+    private boolean finished;
+    private String finalStatus;
+    private boolean finalSettled;
+    private boolean finalEndAcked;
+
+    PubsubWorld(Dst dst) {
+        this.dst = dst;
+        this.ledger = new DstLedger(dst);
+        this.pubsub = new FakePubsub(dst, ledger);
+        this.grouped = dst.chance(0.3);
+        this.maxMessagesPerPoll = dst.pick(List.of(1, 3, 10));
+        pubsub.ackDeadlineSeconds = dst.pick(List.of(10, 20, 60));
+        pubsub.maxDeliveryAttempts = dst.pick(List.of(0, 5));
+        pubsub.pullFailRate = dst.pick(List.of(0.0, 0.05, 0.2));
+        pubsub.ackFailRate = dst.pick(List.of(0.0, 0.05, 0.2));
+        this.processFailRate = dst.pick(List.of(0.0, 0.05, 0.2, 0.6));
+        pubsub.onAck = this::onAck;
+        pubsub.onNack = this::onNack;
+        dst.trace("world: " + config());
+    }
+
+    private String config() {
+        return "mode=" + (grouped ? "GROUPED" : "AUTO") + " 
maxMessagesPerPoll=" + maxMessagesPerPoll + " ackDeadline="
+               + pubsub.ackDeadlineSeconds + " maxDeliveryAttempts=" + 
pubsub.maxDeliveryAttempts + " pullFail="
+               + pubsub.pullFailRate + " ackFail=" + pubsub.ackFailRate + " 
processFail=" + processFailRate;
+    }
+
+    void run() throws Exception {
+        DefaultCamelContext context = DstCamel.newContext(dst);
+        this.context = context;
+        GooglePubsubComponent component = new GooglePubsubComponent() {
+            @Override
+            public SubscriberStub getSubscriberStub(GooglePubsubEndpoint 
endpoint) {
+                return pubsub.newStub();
+            }
+
+            @Override
+            public SubscriptionAdminClient 
getSubscriptionAdminClient(GooglePubsubEndpoint endpoint) {
+                throw new UnsupportedOperationException("maxDeliveryAttempts 
is set on the endpoint");
+            }
+        };
+        component.setAuthenticate(false);
+        context.addComponent("google-pubsub", component);
+        String uri = "google-pubsub:" + FakePubsub.PROJECT + ":" + 
FakePubsub.SUBSCRIPTION
+                     + 
"?synchronousPull=true&concurrentConsumers=1&maxMessagesPerPoll=" + 
maxMessagesPerPoll
+                     + "&ackMode=" + (grouped ? "NONE" : "AUTO") + 
"&maxDeliveryAttempts=" + pubsub.maxDeliveryAttempts;
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                if (grouped) {
+                    from(uri).routeId(ROUTE).autoStartup(false)
+                            .aggregate(constant(true), new 
GroupedExchangeAggregationStrategy())
+                            
.completionSize(maxMessagesPerPoll).completionTimeout(500)
+                            .process(exchange -> processGroup(exchange));
+                } else {
+                    from(uri).routeId(ROUTE).autoStartup(false)
+                            .process(exchange -> process(exchange));
+                }
+            }
+        });
+        context.start();
+        DstExecutor operator = dst.executor("operator", 1);
+        try {
+            operator.schedule("start route", 0, () -> startRoute(context, 
operator));
+            planSends();
+            planOperations(context, operator);
+            operator.schedule("finisher", 1000, () -> finisher(context, 
operator, -1));
+            dst.runUntil(() -> finished, "the finisher");
+            dst.check(
+                    Invariants.of("the consumer uses the subscription as 
documented",
+                            () -> pubsub.violations.isEmpty() && 
violations.isEmpty()
+                                    ? null : pubsub.violations + " " + 
violations + " (" + config() + ")"),
+                    Invariants.of("a delivery is acknowledged only after its 
exchange completed",
+                            () -> wrongAcks.isEmpty() ? null : wrongAcks + " 
(" + config() + ")"),
+                    Invariants.of("a delivery is nacked only after its 
exchange failed or at the max delivery attempts",
+                            () -> wrongNacks.isEmpty() ? null : wrongNacks + " 
(" + config() + ")"),
+                    Invariants.of("a delivery at the max delivery attempts is 
nacked without routing it",
+                            () -> routedAtMax.isEmpty() ? null : routedAtMax + 
" (" + config() + ")"),
+                    Invariants.of("a manual ack of a group acknowledges every 
message of the group",
+                            () -> groupAcks.isEmpty() ? null : groupAcks + " 
(" + config() + ")"),
+                    Invariants.of("a stopped consumer issues no pull, and the 
consumer has one pull at a time",
+                            () -> pubsub.pullsWhileStopped.isEmpty() && 
pubsub.maxPullsInFlight <= 1
+                                    ? null
+                                    : "pulls while stopped " + 
pubsub.pullsWhileStopped + ", at most "
+                                      + pubsub.maxPullsInFlight + " pulls at a 
time (" + config() + ")"),
+                    Invariants.of("every message is acknowledged or dead 
lettered once the faults cleared, and a"
+                                  + " message published then is routed and 
acknowledged",
+                            () -> finalSettled && finalEndAcked && 
"Started".equals(finalStatus)
+                                    ? null
+                                    : "route " + finalStatus + ", unsettled " 
+ pubsub.unsettled() + ", end message "
+                                      + pubsub.stateOf(END) + " (" + config() 
+ ")"));
+        } finally {
+            dst.dropPending();
+            context.stop();
+        }
+    }
+
+    private String deliveryOf(Exchange exchange) {
+        Message m = exchange.getMessage();
+        String ackId = m.getHeader(GooglePubsubConstants.ACK_ID, String.class);
+        return ackId == null ? null : ackId.substring(4);
+    }
+
+    /** ackMode AUTO: one message per exchange; the consumer acks or nacks it 
when the exchange is done. */
+    private void process(Exchange exchange) {
+        String delivery = deliveryOf(exchange);
+        if (delivery == null) {
+            violations.add("an exchange without an ack id");
+            return;
+        }
+        inRoute++;
+        try {
+            ledger.record("routed", "s", delivery);
+            routed(delivery);
+            work(delivery);
+            if (faults && dst.chance(processFailRate)) {
+                failed.add(delivery);
+                ledger.record("failed", "s", delivery);
+                throw Dst.injected(new IllegalStateException("dst: processing 
failed for " + delivery));
+            }
+            completed.add(delivery);
+            ledger.record("completed", "s", delivery);
+        } finally {
+            inRoute--;
+        }
+    }
+
+    /** ackMode NONE: the aggregated exchange of a group, acked or nacked by 
the route with the header. */
+    private void processGroup(Exchange exchange) {
+        List<?> group = exchange.getMessage().getBody(List.class);
+        List<String> deliveries = new ArrayList<>();
+        GooglePubsubAcknowledge acknowledge = null;
+        for (Object o : group) {
+            Exchange e = (Exchange) o;
+            deliveries.add(deliveryOf(e));
+            if (acknowledge == null) {
+                acknowledge = 
e.getMessage().getHeader(GooglePubsubConstants.GOOGLE_PUBSUB_ACKNOWLEDGE,
+                        GooglePubsubAcknowledge.class);
+            }
+        }
+        if (acknowledge == null) {
+            violations.add("a group without the acknowledge header: " + 
deliveries);
+            return;
+        }
+        inRoute++;
+        try {
+            ledger.record("routed", "s", deliveries.toString());
+            deliveries.forEach(this::routed);
+            work(deliveries.toString());
+            if (faults && dst.chance(processFailRate)) {
+                failed.addAll(deliveries);
+                ledger.record("failed", "s", deliveries.toString());
+                acknowledge.nack(exchange);
+                return;
+            }
+            completed.addAll(deliveries);
+            ledger.record("completed", "s", deliveries.toString());
+            acknowledge.ack(exchange);
+            // the ack returned: every message of the group was in it
+            for (String d : deliveries) {
+                if (!acked.contains(d)) {
+                    groupAcks.add("the ack of the group " + deliveries + " did 
not acknowledge " + d);
+                }
+            }
+        } catch (RuntimeException e) {
+            if (!injectedCause(e)) {
+                throw e;
+            }
+            // a failed acknowledgement (injected): the messages are delivered 
again after their deadline
+            ledger.record("ackFailed", "s", deliveries.toString());
+        } finally {
+            inRoute--;
+        }
+    }
+
+    private void work(String what) {
+        if (faults && dst.chance(0.1)) {
+            dst.block(dst.between(pubsub.ackDeadlineSeconds * 500L, 
pubsub.ackDeadlineSeconds * 2000L),
+                    "slow processing of " + what);
+        } else {
+            dst.block(dst.between(0, 200), "processing of " + what);
+        }
+    }
+
+    private void onAck(String delivery) {
+        acked.add(delivery);
+        if (!completed.contains(delivery)) {
+            wrongAcks.add(delivery + " acked at t=" + dst.now() + " but its 
exchange did not complete");
+        }
+    }
+
+    private void onNack(String delivery) {
+        int attempt = 
Integer.parseInt(delivery.substring(delivery.indexOf('#') + 1));
+        boolean atMax = pubsub.maxDeliveryAttempts > 0 && attempt >= 
pubsub.maxDeliveryAttempts;
+        // a delivery that a stopping consumer got from its last pull is 
rejected by the stopped route, so its exchange
+        // fails without being routed, and the consumer nacks it
+        boolean rejectedAtStop = !routed.contains(delivery)
+                && (pubsub.routeStopped || 
context.getRouteController().getRouteStatus(ROUTE) != ServiceStatus.Started);
+        if (!failed.contains(delivery) && !atMax && !rejectedAtStop) {
+            wrongNacks.add(delivery + " nacked at t=" + dst.now() + " but its 
exchange did not fail");
+        }
+    }
+
+    private void routed(String delivery) {
+        routed.add(delivery);
+        int attempt = 
Integer.parseInt(delivery.substring(delivery.indexOf('#') + 1));
+        if (pubsub.maxDeliveryAttempts > 0 && attempt >= 
pubsub.maxDeliveryAttempts) {
+            routedAtMax.add(delivery + " routed at delivery attempt " + 
attempt);
+        }
+    }
+
+    private static boolean injectedCause(Throwable e) {
+        for (Throwable t = e; t != null; t = t.getCause()) {
+            if (t.getMessage() != null && t.getMessage().startsWith("dst: ")) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private GooglePubsubConsumer consumer(DefaultCamelContext context) {
+        return context.getRoute(ROUTE) != null && 
context.getRoute(ROUTE).getConsumer() instanceof GooglePubsubConsumer c
+                ? c : null;
+    }
+
+    private boolean busy(DefaultCamelContext context) {
+        GooglePubsubConsumer c = consumer(context);
+        return inRoute > 0 || c != null && c.getPendingExchangesSize() > 0;
+    }
+
+    /**
+     * Waits for the sends and operations, switches the faults off, waits for 
the subscription to settle (or a
+     * deadline), takes the final state and stops the route.
+     */
+    private void finisher(DefaultCamelContext context, DstExecutor operator, 
long deadline) {
+        if (deadline == -1 && (sendsLeft > 0 || opsLeft > 0)) {
+            operator.schedule("finisher", 500, () -> finisher(context, 
operator, -1));
+            return;
+        }
+        if (deadline == -1) {
+            long slow = dst.between(0, 10_000);
+            dst.trace("world: operations done, faults for another " + slow + " 
ms");
+            operator.schedule("finisher", slow, () -> finisher(context, 
operator, -2));
+            return;
+        }
+        if (deadline == -2) {
+            faults = false;
+            pubsub.faults = false;
+            dst.trace("world: faults cleared");
+            pubsub.publish(END);
+            long d = dst.now() + 30 * 60_000L;
+            operator.schedule("finisher", 500, () -> finisher(context, 
operator, d));
+            return;
+        }
+        ServiceStatus status = 
context.getRouteController().getRouteStatus(ROUTE);
+        boolean settled = pubsub.settled();
+        boolean endAcked = pubsub.stateOf(END).startsWith("ACKED/");
+        if ((busy(context) || !settled || !endAcked || status != 
ServiceStatus.Started) && dst.now() < deadline) {
+            operator.schedule("finisher", 500, () -> finisher(context, 
operator, deadline));
+            return;
+        }
+        finalStatus = String.valueOf(status);
+        finalSettled = settled;
+        finalEndAcked = endAcked;
+        if (busy(context)) {
+            violations.add("an exchange is still in the route at the 
deadline");
+        } else {
+            // the pull loop runs for ever: the stop cancels its pull, so that 
it ends and the run can end
+            try {
+                context.getRouteController().stopRoute(ROUTE);
+                pubsub.routeStopped = true;
+            } catch (Exception e) {
+                violations.add("final stop failed: " + e);
+            }
+        }
+        finished = true;
+    }
+
+    private void startRoute(DefaultCamelContext context, DstExecutor operator) 
{
+        try {
+            pubsub.routeStopped = false;
+            context.getRouteController().startRoute(ROUTE);
+            ledger.record("routeStarted", "r", ROUTE);
+        } catch (Exception e) {
+            ledger.record("routeStartFailed", "r", ROUTE);
+            violations.add("start failed: " + e);
+        }
+    }
+
+    private void planSends() {
+        DstExecutor publisher = dst.executor("publisher", 1);
+        long t = dst.between(0, 500);
+        int n = 0;
+        int bursts = (int) dst.between(1, 4);
+        for (int b = 0; b < bursts; b++) {
+            int size = (int) dst.between(1, 15);
+            for (int i = 0; i < size; i++) {
+                String id = "m" + n++;
+                sendsLeft++;
+                publisher.schedule("publish " + id, t, () -> {
+                    pubsub.publish(id);
+                    sendsLeft--;
+                });
+                t += dst.between(0, 100);
+            }
+            t += dst.between(0, 20_000);
+        }
+    }
+
+    private void planOperations(DefaultCamelContext context, DstExecutor 
operator) {
+        int ops = (int) dst.between(0, 3);
+        long t = dst.between(500, 3000);
+        for (int i = 0; i < ops; i++) {
+            opsLeft++;
+            if (grouped || dst.chance(0.5)) {
+                operator.schedule("stop route", t, () -> stopWhenIdle(context, 
operator));
+            } else {
+                operator.schedule("restart consumer", t, () -> 
restartConsumerWhenIdle(context, operator));
+            }
+            t += dst.between(1000, 20_000);
+        }
+    }
+
+    /**
+     * Stops the consumer once it is idle and starts the same consumer again 
at once, in the same task, as a throttling
+     * route policy does (RoutePolicySupport.stopConsumer and startConsumer): 
the pull loop of the previous start sees
+     * its cancelled pull only after the start, and must end then instead of 
pulling next to the loop of the new start.
+     * Only with ackMode AUTO: with GROUPED the loop of the new start could 
run nested above the processing of a group
+     * that the aggregator completes later, and on the one stack it would 
never let that processing resume.
+     */
+    private void restartConsumerWhenIdle(DefaultCamelContext context, 
DstExecutor operator) {
+        GooglePubsubConsumer c = consumer(context);
+        if (c == null || context.getRouteController().getRouteStatus(ROUTE) != 
ServiceStatus.Started) {
+            opsLeft--;
+            return;
+        }
+        if (busy(context)) {
+            operator.schedule("restart consumer (busy)", 50, () -> 
restartConsumerWhenIdle(context, operator));
+            return;
+        }
+        try {
+            ServiceHelper.stopService(c);
+            ledger.record("consumerStopped", "r", ROUTE);
+            ServiceHelper.startService(c);
+            ledger.record("consumerStarted", "r", ROUTE);
+        } catch (Exception e) {
+            violations.add("consumer restart failed: " + e);
+        }
+        opsLeft--;
+    }
+
+    /**
+     * Stops the route once no exchange is in it and the consumer has no 
pending exchange (a stop nested above one on
+     * the one stack would wait for it for ever), then starts it again after a 
while: the pull loop of the stopped
+     * consumer ends as soon as the stop returned, when its cancelled pull 
answers.
+     */
+    private void stopWhenIdle(DefaultCamelContext context, DstExecutor 
operator) {
+        if (context.getRouteController().getRouteStatus(ROUTE) != 
ServiceStatus.Started) {
+            opsLeft--;
+            return;
+        }
+        if (busy(context)) {
+            operator.schedule("stop route (busy)", 50, () -> 
stopWhenIdle(context, operator));
+            return;
+        }
+        try {
+            context.getRouteController().stopRoute(ROUTE);
+            pubsub.routeStopped = true;
+            ledger.record("routeStopped", "r", ROUTE);
+        } catch (Exception e) {
+            violations.add("stop failed: " + e);
+        }
+        operator.schedule("start route", dst.between(100, 5000), () -> {
+            startRoute(context, operator);
+            opsLeft--;
+        });
+    }
+}
diff --git 
a/components/camel-google/camel-google-pubsub/src/test/resources/log4j2.properties
 
b/components/camel-google/camel-google-pubsub/src/test/resources/log4j2.properties
index d550bf09242b..eb7d45ee5f68 100644
--- 
a/components/camel-google/camel-google-pubsub/src/test/resources/log4j2.properties
+++ 
b/components/camel-google/camel-google-pubsub/src/test/resources/log4j2.properties
@@ -16,9 +16,16 @@
 ## ---------------------------------------------------------------------------
 
 
-appender.file.type = File
+# capped: the DST test runs the consumer for a thousand seeds
+appender.file.type = RollingFile
 appender.file.name = file
 appender.file.fileName = target/camel-google-pubsub-test.log
+appender.file.filePattern = target/camel-google-pubsub-test.%i.log
+appender.file.policies.type = Policies
+appender.file.policies.size.type = SizeBasedTriggeringPolicy
+appender.file.policies.size.size = 50MB
+appender.file.strategy.type = DefaultRolloverStrategy
+appender.file.strategy.max = 1
 appender.file.layout.type = PatternLayout
 appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
 appender.out.type = Console
diff --git a/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc 
b/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
index 549386f731d8..ffdc45e6d8a6 100644
--- a/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
+++ b/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
@@ -81,6 +81,16 @@ a|* checkpointing by checkpointBatchSize and 
checkpointBatchTimeout
 * an asynchronous downstream step
 |CAMEL-25683, CAMEL-25738, CAMEL-25781
 
+|camel-google-pubsub
+|`PubsubWorld` (`PubsubConsumerDstTest`)
+|FakePubsub: a subscription (Pull, Acknowledge, ModifyAckDeadline, ack 
deadlines, dead letter policy) behind the SubscriberStub of synchronousPull
+a|* synchronousPull with ackMode AUTO, and ackMode NONE with grouped messages 
acked or nacked together
+* ack deadlines that expire while a message is processed
+* the max delivery attempts of a subscription with a dead letter policy
+* route stop and start while the consumer pulls
+* a stop and start of the same consumer in one step, as a throttling route 
policy does
+|CAMEL-25712, CAMEL-25790, CAMEL-26647
+
 |camel-kafka-share
 |`KafkaShareWorld` (`KafkaShareConsumerDstTest`)
 |FakeShareGroup: a share group (KIP-932) of one topic with one partition, 
behind ShareConsumer

Reply via email to