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 c4fa39643ed2 CAMEL-27495: camel-google-pubsub - synchronousPull
retries a failed pull after the retry delay, not in a tight loop (#30829)
c4fa39643ed2 is described below
commit c4fa39643ed218ad8e0be710aa8b7f0facd74e90
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:31:54 2026 +0530
CAMEL-27495: camel-google-pubsub - synchronousPull retries a failed pull
after the retry delay, not in a tight loop (#30829)
With synchronousPull=true, each loop builds a SubscriberStub for every pull,
which loads the credentials of the endpoint. When they could not be loaded
(a removed or rotated key file, no Application Default Credentials, a
metadata server that does not answer), getSubscriberStub threw IOException
and the loop logged it with a stack trace and pulled again at once: about
44,000 attempts per second from one loop, a full CPU core and a log that
grew by tens of MB per second, until the credentials came back. A pull that
failed at once with a retryable code was pulled again at once too. The
asynchronous loop waits 5 seconds after a recoverable error.
- After a failed attempt (IOException, retryable ApiException) the
synchronous loop waits until the retry delay has passed since the attempt
started: the 5 seconds of the asynchronous loop, now a field both loops
use. An attempt that already took that long (a retryable error that the
client library retried for a minute) is followed by the next pull at once.
The wait is a BackgroundTask on the PubSubReconnectTask scheduler, as in
the asynchronous loop; it is skipped when the consumer no longer pulls,
a stop of the consumer ends a wait in progress at once, and an interrupt
during it ends the loop.
- The first failed attempt in a row is logged at ERROR with its stack trace
as before, the next ones in one WARN line (stack trace at DEBUG), and the
first pull that works again at INFO.
- PubsubConsumerDstTest rewrites org.apache.camel.support.task too, so the
wait of BackgroundTask.run is a virtual wait in the DST world.
- GooglePubsubConsumerSyncPullRetryDelayTest: credentials that cannot be
loaded, and a pull failing at once with UNAVAILABLE: at most 4 attempts
within 2 seconds with a retry delay of 1 second, then the message is
received once the failure is gone; and a route stop during a retry delay
of one minute ends the wait at once.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../google/pubsub/GooglePubsubConsumer.java | 101 +++++++++-
...GooglePubsubConsumerSyncPullRetryDelayTest.java | 204 +++++++++++++++++++++
.../google/pubsub/dst/PubsubConsumerDstTest.java | 3 +-
3 files changed, 304 insertions(+), 4 deletions(-)
diff --git
a/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
index 132a30097d71..e04a0756c6bc 100644
---
a/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
+++
b/components/camel-google/camel-google-pubsub/src/main/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumer.java
@@ -26,6 +26,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -56,6 +57,7 @@ import org.apache.camel.spi.ShutdownAware;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.support.DefaultConsumer;
import org.apache.camel.support.UnitOfWorkHelper;
+import org.apache.camel.support.task.BackgroundTask;
import org.apache.camel.support.task.Tasks;
import org.apache.camel.support.task.budget.Budgets;
import org.slf4j.Logger;
@@ -74,6 +76,14 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
* pulling again, also when the consumer has been started again meanwhile.
*/
private final AtomicLong generation = new AtomicLong();
+ /**
+ * How long a subscriber loop waits before it subscribes or pulls again
after a failure.
+ */
+ private Duration retryDelay = Duration.ofSeconds(5);
+ /**
+ * The retry delays the subscriber loops wait in now: a stop ends them at
once, as the loops do not pull again.
+ */
+ private final Set<BackgroundTask> retryWaits =
ConcurrentHashMap.newKeySet();
private ExecutorService executor;
private ScheduledExecutorService taskExecutor;
private final List<Subscriber> subscribers;
@@ -133,6 +143,7 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
localLog.info("Stopping Google PubSub consumer for {}/{}",
endpoint.getProjectId(), endpoint.getDestinationName());
generation.incrementAndGet();
+ cancelRetryWaits();
if (!subscribers.isEmpty()) {
localLog.info("Stopping subscribers for {}/{}",
endpoint.getProjectId(), endpoint.getDestinationName());
subscribers.forEach(AbstractApiService::stopAsync);
@@ -168,6 +179,7 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
// Note: when a stopRoute with abortAfterTimeout=true times out, the
route is started again while this consumer
// is still started, so doStart does not run and no loop pulls again
until the route is stopped and started
generation.incrementAndGet();
+ cancelRetryWaits();
if (!subscribers.isEmpty()) {
subscribers.forEach(AbstractApiService::stopAsync);
}
@@ -185,6 +197,13 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
// noop
}
+ private void cancelRetryWaits() {
+ // a loop that waits does not pull again after a stop: end the wait
now instead of after the retry delay (in
+ // doShutdown the scheduler of the wait is shut down, which would
leave the loop waiting until its thread is
+ // interrupted)
+ retryWaits.forEach(wait -> wait.cancel(false));
+ }
+
private void safeCancelSynchronousPullResponses() {
for (ApiFuture<PullResponse> pullResponseApiFuture :
pendingSynchronousPullResponses) {
try {
@@ -230,6 +249,13 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
return resolvedMaxDeliveryAttempts;
}
+ /**
+ * For tests: the retry delay of the subscriber loops (5 seconds by
default), set before the consumer starts.
+ */
+ void setRetryDelay(Duration retryDelay) {
+ this.retryDelay = retryDelay;
+ }
+
public void incrementPendingExchanges() {
pendingExchanges.incrementAndGet();
}
@@ -242,6 +268,8 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
private final String subscriptionName;
private final long wrapperGeneration;
+ // failed attempts since the last pull or subscription that worked;
only used by the thread of this loop
+ private int failuresInARow;
SubscriberWrapper(long wrapperGeneration) {
this.wrapperGeneration = wrapperGeneration;
@@ -334,7 +362,7 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
Tasks.backgroundTask()
.withBudget(Budgets.iterationTimeBudget()
.withMaxIterations(1)
- .withInitialDelay(Duration.ofSeconds(5))
+ .withInitialDelay(retryDelay)
.withInterval(Duration.ofMillis(1))
.withUnlimitedDuration()
.build())
@@ -355,6 +383,7 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
private void synchronousPull(String subscriptionName) throws
ExecutionException, InterruptedException {
while (isPullAllowed()) {
+ long attemptStarted = System.nanoTime();
ApiFuture<PullResponse> synchronousPullResponseFuture = null;
try (SubscriberStub subscriber =
endpoint.getComponent().getSubscriberStub(endpoint)) {
@@ -371,6 +400,7 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
synchronousPullResponseFuture.cancel(true);
}
PullResponse pullResponse =
synchronousPullResponseFuture.get();
+ pulled();
for (ReceivedMessage message :
pullResponse.getReceivedMessagesList()) {
PubsubMessage pubsubMessage = message.getMessage();
Exchange exchange = createExchange(true);
@@ -468,10 +498,13 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
} catch (CancellationException e) {
localLog.debug("PubSub synchronous pull request
cancelled", e);
} catch (IOException e) {
- localLog.error("I/O exception while getting messages from
PubSub. Reconnecting.", e);
+ // such as credentials that cannot be loaded: an attempt
at once would fail the same way
+ logFailure("I/O exception while getting messages from
PubSub. Reconnecting.", e);
+ waitBeforeRetry(attemptStarted);
} catch (ExecutionException e) {
if (e.getCause() instanceof ApiException &&
((ApiException) (e.getCause())).isRetryable()) {
- localLog.error("Retryable API exception in getting
messages from PubSub", e.getCause());
+ logFailure("Retryable API exception in getting
messages from PubSub", e.getCause());
+ waitBeforeRetry(attemptStarted);
} else {
throw e;
}
@@ -482,5 +515,67 @@ public class GooglePubsubConsumer extends DefaultConsumer
implements ShutdownAwa
}
}
}
+
+ /**
+ * Logs a failed attempt: the first one in a row with its stack trace,
the next ones in one line (the stack
+ * trace at DEBUG), as the loop retries until the cause is gone.
+ */
+ private void logFailure(String message, Throwable e) {
+ if (failuresInARow++ == 0) {
+ localLog.error(message, e);
+ } else {
+ localLog.warn("{} ({} failed attempts in a row: {})", message,
failuresInARow, e.toString());
+ localLog.debug(message, e);
+ }
+ }
+
+ /**
+ * A pull or a subscription worked: logs once that the loop recovered
from failed attempts.
+ */
+ private void pulled() {
+ if (failuresInARow > 0) {
+ localLog.info("Getting messages from PubSub {} again after {}
failed attempts", subscriptionName,
+ failuresInARow);
+ failuresInARow = 0;
+ }
+ }
+
+ /**
+ * Waits after a failed attempt until the retry delay has passed since
the attempt started, so a loop makes at
+ * most one failed attempt per retry delay. An attempt that already
took that long (a retryable error is only
+ * returned after the client library retried it for up to a minute) is
followed by the next one at once. A stop
+ * of the consumer ends the wait.
+ */
+ private void waitBeforeRetry(long attemptStarted) throws
InterruptedException {
+ long remaining = retryDelay.toMillis() -
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - attemptStarted);
+ ScheduledExecutorService scheduler = taskExecutor;
+ if (remaining <= 0 || scheduler == null || !isPullAllowed()) {
+ return;
+ }
+ BackgroundTask wait = Tasks.backgroundTask()
+ .withBudget(Budgets.iterationTimeBudget()
+ .withMaxIterations(1)
+ .withInitialDelay(Duration.ofMillis(remaining))
+ .withInterval(Duration.ofMillis(1))
+ .withUnlimitedDuration()
+ .build())
+ .withScheduledExecutor(scheduler)
+ .withName("PubSubRetryDelay")
+ .build();
+ retryWaits.add(wait);
+ try {
+ // a stop cancels the waits in retryWaits after it stopped the
pulling: a stop that came before this
+ // wait was added is seen here, a later one cancels it (also
before it runs, then it returns at once)
+ if (isPullAllowed()) {
+ wait.run(getEndpoint().getCamelContext(), () -> true);
+ }
+ } finally {
+ retryWaits.remove(wait);
+ }
+ // the wait returns at once when the thread is interrupted
(shutdown): end the loop instead of retrying
+ if (Thread.interrupted()) {
+ throw new InterruptedException("Interrupted while waiting to
get messages from PubSub again");
+ }
+ }
}
}
diff --git
a/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerSyncPullRetryDelayTest.java
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerSyncPullRetryDelayTest.java
new file mode 100644
index 000000000000..cb858f5c7c91
--- /dev/null
+++
b/components/camel-google/camel-google-pubsub/src/test/java/org/apache/camel/component/google/pubsub/GooglePubsubConsumerSyncPullRetryDelayTest.java
@@ -0,0 +1,204 @@
+/*
+ * 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;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.api.core.ApiFuture;
+import com.google.api.core.ApiFutures;
+import com.google.api.core.SettableApiFuture;
+import com.google.api.gax.grpc.GrpcStatusCode;
+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.pubsub.v1.AcknowledgeRequest;
+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 io.grpc.Status;
+import org.apache.camel.CamelContext;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.PluginHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * With synchronous pull, a pull that fails at once (credentials that cannot
be loaded, an error the client library
+ * returns without retrying it for long) must be attempted again only after
the retry delay, as the asynchronous
+ * consumer does, and not in a tight loop; once the error is gone the consumer
must receive messages again.
+ */
+class GooglePubsubConsumerSyncPullRetryDelayTest {
+
+ private static final Duration RETRY_DELAY = Duration.ofSeconds(1);
+
+ private final CamelContext context = new DefaultCamelContext();
+ private final SettableApiFuture<PullResponse> pending =
SettableApiFuture.create();
+ private final AtomicBoolean failing = new AtomicBoolean(true);
+ private final AtomicInteger attempts = new AtomicInteger();
+
+ @AfterEach
+ void tearDown() {
+ pending.cancel(true);
+ context.stop();
+ }
+
+ @Test
+ void credentialsThatCannotBeLoadedAreRetriedAfterTheDelay() throws
Exception {
+ SubscriberStub stub = stub(request ->
ApiFutures.immediateFuture(message()));
+ startRoute(new GooglePubsubComponent() {
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) throws IOException {
+ attempts.incrementAndGet();
+ if (failing.get()) {
+ throw new FileNotFoundException("the service account key
file was removed");
+ }
+ return stub;
+ }
+ });
+
+ assertAttemptsBoundedThenReceives();
+ }
+
+ @Test
+ void pullFailingAtOnceWithRetryableErrorIsRetriedAfterTheDelay() throws
Exception {
+ SubscriberStub stub = stub(request -> {
+ attempts.incrementAndGet();
+ if (failing.get()) {
+ return ApiFutures.immediateFailedFuture(new
UnavailableException(
+ "Pub/Sub unavailable", null,
GrpcStatusCode.of(Status.Code.UNAVAILABLE), true));
+ }
+ return ApiFutures.immediateFuture(message());
+ });
+ startRoute(new GooglePubsubComponent() {
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) {
+ return stub;
+ }
+ });
+
+ assertAttemptsBoundedThenReceives();
+ }
+
+ @Test
+ void stopDuringTheRetryDelayEndsTheWait() throws Exception {
+ startRoute(new GooglePubsubComponent() {
+ @Override
+ public SubscriberStub getSubscriberStub(GooglePubsubEndpoint
endpoint) throws IOException {
+ attempts.incrementAndGet();
+ throw new FileNotFoundException("the service account key file
was removed");
+ }
+ }, Duration.ofMinutes(1));
+
+ await().atMost(Duration.ofSeconds(10)).until(this::waitingForRetry);
+ context.getRouteController().stopRoute("pubsub");
+
+ // the loop does not wait the rest of the minute: it ends with the stop
+ await().atMost(Duration.ofSeconds(5)).until(() -> !waitingForRetry());
+ assertEquals(1, attempts.get());
+ }
+
+ private boolean waitingForRetry() {
+ return
PluginHelper.getTaskManagerRegistry(context.getCamelContextExtension()).getTasks().stream()
+ .anyMatch(task -> "PubSubRetryDelay".equals(task.getName()));
+ }
+
+ private void assertAttemptsBoundedThenReceives() throws Exception {
+ MockEndpoint result = context.getEndpoint("mock:result",
MockEndpoint.class);
+ result.expectedBodiesReceived("hello");
+ result.setResultWaitTime(10000);
+
+ await().atMost(Duration.ofSeconds(10)).until(() -> attempts.get() >=
1);
+ // one attempt per retry delay of 1 second, not one after the other:
at most 3 more within 2 seconds
+
await().during(Duration.ofSeconds(2)).atMost(Duration.ofSeconds(3)).until(() ->
attempts.get() <= 4);
+
+ failing.set(false);
+ result.assertIsSatisfied();
+ }
+
+ private void startRoute(GooglePubsubComponent component) throws Exception {
+ startRoute(component, RETRY_DELAY);
+ }
+
+ private void startRoute(GooglePubsubComponent component, Duration
retryDelay) throws Exception {
+ context.addComponent("google-pubsub", component);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("google-pubsub:test-project:test-subscription?synchronousPull=true&maxDeliveryAttempts=5")
+ .routeId("pubsub").autoStartup(false)
+ .to("mock:result");
+ }
+ });
+ context.start();
+ ((GooglePubsubConsumer)
context.getRoute("pubsub").getConsumer()).setRetryDelay(retryDelay);
+ context.getRouteController().startRoute("pubsub");
+ }
+
+ @SuppressWarnings("unchecked")
+ private SubscriberStub stub(PullAnswer firstPulls) {
+ AtomicBoolean received = new AtomicBoolean();
+ UnaryCallable<PullRequest, PullResponse> pullCallable =
mock(UnaryCallable.class);
+
when(pullCallable.futureCall(any(PullRequest.class))).thenAnswer(invocation -> {
+ if (received.get()) {
+ // no more messages; cancelled when the consumer stops
+ return pending;
+ }
+ ApiFuture<PullResponse> response =
firstPulls.answer(invocation.getArgument(0));
+ if (!failing.get()) {
+ received.set(true);
+ }
+ return response;
+ });
+ UnaryCallable<AcknowledgeRequest, Empty> acknowledgeCallable =
mock(UnaryCallable.class);
+
when(acknowledgeCallable.call(any(AcknowledgeRequest.class))).thenReturn(Empty.getDefaultInstance());
+
+ SubscriberStub stub = mock(SubscriberStub.class);
+ when(stub.pullCallable()).thenReturn(pullCallable);
+ when(stub.acknowledgeCallable()).thenReturn(acknowledgeCallable);
+ return stub;
+ }
+
+ private static PullResponse message() {
+ return PullResponse.newBuilder()
+ .addReceivedMessages(ReceivedMessage.newBuilder()
+ .setAckId("ack-1")
+ .setMessage(PubsubMessage.newBuilder()
+ .setMessageId("m1")
+ .setData(ByteString.copyFromUtf8("hello"))))
+ .build();
+ }
+
+ @FunctionalInterface
+ private interface PullAnswer {
+ ApiFuture<PullResponse> answer(PullRequest request);
+ }
+}
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
index 887c63f5e9b9..81cf282481f1 100644
---
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
@@ -28,7 +28,8 @@ import org.apache.camel.test.dst.DstTest;
* 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")
+// the retry delay of the subscriber loops waits in BackgroundTask.run, which
must be a virtual wait
+@DstInstrument(value = "org.apache.camel.component.google.pubsub", alsoRewrite
= "org.apache.camel.support.task")
class PubsubConsumerDstTest {
@DstTest(seeds = 1000)