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 f51cbd229c7f CAMEL-27494: camel-google-secret-manager - a Pub/Sub 
subscriber that failed is replaced at the next refresh (#30828)
f51cbd229c7f is described below

commit f51cbd229c7f959b6622bcdfaf103709ab7d7ed7
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:31:41 2026 +0530

    CAMEL-27494: camel-google-secret-manager - a Pub/Sub subscriber that failed 
is replaced at the next refresh (#30828)
    
    PubsubReloadTriggerTask receives the secret events of the GCP refresh
    from a Google Pub/Sub Subscriber that it builds once, in doStart. run()
    (each refresh period, on the timer thread that the periodic tasks of the
    CamelContext share) started the Subscriber only when it was NEW. A
    Subscriber that fails, for example on a status of its streaming pull that
    it does not retry, such as PERMISSION_DENIED while an IAM binding is
    changed or NOT_FOUND, goes to FAILED and cannot be started again. run()
    left it there for good: no secret event was received any more, so no
    later secret rotation reloaded the CamelContext until a restart. The
    failure was logged only at DEBUG (the IllegalStateException of
    awaitRunning(), ignored by the timer), and run() still set lastCheckTime
    on every refresh, so the dev console showed a recent check.
    
    run() now replaces a Subscriber that is FAILED (or TERMINATED while the
    task is started) with a new one, built the same way (doStart keeps a
    factory with the subscription name and the credentials), and starts it.
    That is one new Subscriber per refresh at most. The first replacement in
    a row is logged at WARN with the root cause of the failure (the gRPC
    status of the streaming pull; the Subscriber's own failure cause only
    says that an inner service failed, its stack trace goes to DEBUG), the
    repeats at DEBUG, and a Subscriber that runs again at INFO. A new
    Subscriber reports running before the service answers its streaming pull,
    so one that replaced a failed Subscriber counts as running (INFO,
    lastCheckTime) only when it is still running at the next refresh: while
    the streaming pull keeps being refused, that gives one WARN and a last
    check that does not move. The old Subscriber needs no stop: a Subscriber
    whose streaming pull fails shuts its connections, executors and stub down
    itself. run() waits at most 5 seconds for the Subscriber to be running
    (awaitRunning had no deadline and could hold the shared timer thread, and
    so every other periodic task, for as long as a start hung). A start that
    hangs now holds the timer thread for at most 5 seconds per new
    Subscriber; a Subscriber still starting is looked at again at the next
    refresh, one that failed while starting is replaced then. lastCheckTime
    is now set only when the Subscriber is running, as above (and, as before,
    when the task has no Subscriber). If Camel stops while run() starts a new
    Subscriber, run() stops it, so doShutdown cannot miss it. The subscriber
    field is volatile, as doShutdown runs on another thread.
    
    New PubsubReloadTriggerTaskSubscriberFailedTest: the real Subscriber
    against an in-process fake of the Pub/Sub Subscriber service (gRPC),
    scheduled with the CamelContext's period task scheduler. The streaming
    pull is first refused with PERMISSION_DENIED (the Subscriber goes to
    FAILED), then allowed with one event of a new version of the watched
    secret: a new Subscriber is running, the reload happens, the failure is
    logged at WARN, the new Subscriber still running at the next refresh at
    INFO, and stopping Camel stops the new Subscriber. A second test refuses
    every streaming pull 50 ms after it starts (as over a network, so each
    new Subscriber reports running first; refresh period 500 ms): after five
    Subscribers there is one WARN, no INFO, and lastCheckTime has not moved
    since the first failure.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../manager/vault/PubsubReloadTriggerTask.java     | 109 +++++++-
 ...ubsubReloadTriggerTaskSubscriberFailedTest.java | 303 +++++++++++++++++++++
 2 files changed, 397 insertions(+), 15 deletions(-)

diff --git 
a/components/camel-google/camel-google-secret-manager/src/main/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTask.java
 
b/components/camel-google/camel-google-secret-manager/src/main/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTask.java
index 6edf740236fb..a5cbab6bd0d2 100644
--- 
a/components/camel-google/camel-google-secret-manager/src/main/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTask.java
+++ 
b/components/camel-google/camel-google-secret-manager/src/main/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTask.java
@@ -23,8 +23,12 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Supplier;
 
 import com.google.api.core.ApiService;
+import com.google.api.gax.core.CredentialsProvider;
 import com.google.api.gax.core.FixedCredentialsProvider;
 import com.google.auth.Credentials;
 import com.google.auth.oauth2.GoogleCredentials;
@@ -66,7 +70,14 @@ public class PubsubReloadTriggerTask extends ServiceSupport 
implements CamelCont
     private CamelContext camelContext;
     private boolean reloadEnabled = true;
     private String secrets;
-    private Subscriber subscriber;
+    // run() runs on the timer thread that all the periodic tasks of the 
CamelContext share: how long it waits for the
+    // subscriber it starts to be running
+    private static final long SUBSCRIBER_START_TIMEOUT = 5000;
+    // builds a new subscriber with the receiver of this task: set by doStart 
(package-private for tests)
+    Supplier<Subscriber> subscriberFactory;
+    private volatile Subscriber subscriber;
+    // subscribers in a row that failed or stopped (only used by run(), on the 
timer thread)
+    private int failedSubscribers;
     private GoogleSecretManagerPropertiesFunction propertiesFunction;
     private volatile Instant lastCheckTime;
     private volatile Instant lastReloadTime;
@@ -104,7 +115,8 @@ public class PubsubReloadTriggerTask extends ServiceSupport 
implements CamelCont
     }
 
     /**
-     * Last time this task checked GCP for updated secrets.
+     * Last time this task checked GCP for updated secrets: the last refresh 
that found the Google Pub/Sub subscriber
+     * running (or that ran before the task was started).
      */
     public Instant getLastCheckTime() {
         return lastCheckTime;
@@ -149,25 +161,25 @@ public class PubsubReloadTriggerTask extends 
ServiceSupport implements CamelCont
                 subscription = gcpVaultConfiguration.getSubscriptionName();
             }
         }
+        CredentialsProvider credentialsProvider;
         if (ObjectHelper.isNotEmpty(serviceAccountKey) && 
ObjectHelper.isNotEmpty(projectId)
                 && ObjectHelper.isNotEmpty(subscription)) {
             InputStream resolveMandatoryResourceAsInputStream
                     = 
ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), 
serviceAccountKey);
             Credentials myCredentials = ServiceAccountCredentials
                     .fromStream(resolveMandatoryResourceAsInputStream);
-            ProjectSubscriptionName subscriptionName = 
ProjectSubscriptionName.of(projectId, subscription);
-            Subscriber.Builder builder = 
Subscriber.newBuilder(subscriptionName, new FilteringEventMessageReceiver());
-            
builder.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials));
-            subscriber = builder.build();
+            credentialsProvider = 
FixedCredentialsProvider.create(myCredentials);
         } else if (useDefaultInstance && ObjectHelper.isNotEmpty(projectId) && 
ObjectHelper.isNotEmpty(subscription)) {
-            ProjectSubscriptionName subscriptionName = 
ProjectSubscriptionName.of(projectId, subscription);
-            Subscriber.Builder builder = 
Subscriber.newBuilder(subscriptionName, new FilteringEventMessageReceiver());
-            
builder.setCredentialsProvider(FixedCredentialsProvider.create(GoogleCredentials.getApplicationDefault()));
-            subscriber = builder.build();
+            credentialsProvider = 
FixedCredentialsProvider.create(GoogleCredentials.getApplicationDefault());
         } else {
             throw new RuntimeCamelException(
                     "Using the GCP Secret refresh task requires setting GCP 
service account key, project Id and Google Pubsub subscription name as 
application properties or environment variables");
         }
+        ProjectSubscriptionName subscriptionName = 
ProjectSubscriptionName.of(projectId, subscription);
+        subscriberFactory = () -> Subscriber.newBuilder(subscriptionName, new 
FilteringEventMessageReceiver())
+                .setCredentialsProvider(credentialsProvider)
+                .build();
+        subscriber = subscriberFactory.get();
     }
 
     @Override
@@ -188,15 +200,82 @@ public class PubsubReloadTriggerTask extends 
ServiceSupport implements CamelCont
 
     @Override
     public void run() {
-        lastCheckTime = Instant.now();
-
-        if (subscriber == null) {
+        Subscriber current = subscriber;
+        if (current == null) {
+            lastCheckTime = Instant.now();
             return;
         }
+        ApiService.State state = current.state();
+        // running at the previous refresh already, so its streaming pull 
works: a subscriber that has just started
+        // reports RUNNING before the service answers its streaming pull, 
which can still be refused right after
+        boolean runningSincePreviousRefresh = state == 
ApiService.State.RUNNING;
+        if (state == ApiService.State.FAILED || state == 
ApiService.State.TERMINATED) {
+            if (!isRunAllowed()) {
+                return;
+            }
+            // a Subscriber that failed (for example on a non-retryable status 
of its streaming pull, such as
+            // PERMISSION_DENIED) receives nothing any more and cannot be 
started again: replace it with a new one
+            failedSubscribers++;
+            logSubscriberNotRunning(current, state);
+            current = subscriberFactory.get();
+            subscriber = current;
+            state = current.state();
+        }
         // the subscriber is push based, so it only has to be started once. A 
Google ApiService can only be
         // started while it is still NEW, starting it again on every period 
would fail with an IllegalStateException
-        if (subscriber.state() == ApiService.State.NEW) {
-            subscriber.startAsync().awaitRunning();
+        if (state == ApiService.State.NEW) {
+            current.startAsync();
+            if (!isRunAllowed()) {
+                // stopped meanwhile: doShutdown may have missed the new 
subscriber
+                current.stopAsync();
+                return;
+            }
+            try {
+                // run() runs on the timer thread that all the periodic tasks 
of the CamelContext share: do not wait
+                // without a bound
+                current.awaitRunning(SUBSCRIBER_START_TIMEOUT, 
TimeUnit.MILLISECONDS);
+            } catch (TimeoutException e) {
+                LOG.debug("The Google Pub/Sub subscriber of the GCP secret 
refresh task is not running after {} ms,"
+                          + " it is checked again at the next refresh",
+                        SUBSCRIBER_START_TIMEOUT);
+            } catch (IllegalStateException e) {
+                // it failed while starting: it is reported and replaced at 
the next refresh
+                LOG.debug("The Google Pub/Sub subscriber of the GCP secret 
refresh task failed to start", e);
+            }
+        }
+        // only a running subscriber receives the secret events: the dev 
console shows a stale last check otherwise. A
+        // subscriber that replaced a failed one counts once it is still 
running at the next refresh, so that while
+        // the streaming pull keeps being refused there is one WARN, and the 
last check does not move
+        if (current.state() == ApiService.State.RUNNING && (failedSubscribers 
== 0 || runningSincePreviousRefresh)) {
+            lastCheckTime = Instant.now();
+            if (failedSubscribers > 0) {
+                LOG.info("The Google Pub/Sub subscriber of the GCP secret 
refresh task is running again, after {}"
+                         + " subscriber(s) that did not run",
+                        failedSubscribers);
+                failedSubscribers = 0;
+            }
+        }
+    }
+
+    private void logSubscriberNotRunning(Subscriber current, ApiService.State 
state) {
+        String cause = "stopped";
+        if (state == ApiService.State.FAILED) {
+            // the failure cause of the Subscriber wraps the failure of its 
streaming pull (the gRPC status)
+            Throwable root = current.failureCause();
+            while (root.getCause() != null && root.getCause() != root) {
+                root = root.getCause();
+            }
+            cause = root.toString();
+            LOG.debug("The Google Pub/Sub subscriber of the GCP secret refresh 
task failed", current.failureCause());
+        }
+        if (failedSubscribers == 1) {
+            // the first one in a row at WARN, the repeats at DEBUG (a 
subscriber that runs again is logged at INFO)
+            LOG.warn("The Google Pub/Sub subscriber of the GCP secret refresh 
task is {} ({}): starting a new subscriber",
+                    state, cause);
+        } else {
+            LOG.debug("The Google Pub/Sub subscriber of the GCP secret refresh 
task is {} ({}), {} times in a row:"
+                      + " starting a new subscriber",
+                    state, cause, failedSubscribers);
         }
     }
 
diff --git 
a/components/camel-google/camel-google-secret-manager/src/test/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTaskSubscriberFailedTest.java
 
b/components/camel-google/camel-google-secret-manager/src/test/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTaskSubscriberFailedTest.java
new file mode 100644
index 000000000000..c5d80068fb08
--- /dev/null
+++ 
b/components/camel-google/camel-google-secret-manager/src/test/java/org/apache/camel/component/google/secret/manager/vault/PubsubReloadTriggerTaskSubscriberFailedTest.java
@@ -0,0 +1,303 @@
+/*
+ * 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.secret.manager.vault;
+
+import java.lang.reflect.Field;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.api.core.ApiService;
+import com.google.api.gax.core.NoCredentialsProvider;
+import com.google.api.gax.grpc.GrpcTransportChannel;
+import com.google.api.gax.rpc.FixedTransportChannelProvider;
+import com.google.cloud.pubsub.v1.Subscriber;
+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.ProjectSubscriptionName;
+import com.google.pubsub.v1.PubsubMessage;
+import com.google.pubsub.v1.ReceivedMessage;
+import com.google.pubsub.v1.StreamingPullRequest;
+import com.google.pubsub.v1.StreamingPullResponse;
+import io.grpc.ManagedChannel;
+import io.grpc.MethodDescriptor;
+import io.grpc.Server;
+import io.grpc.ServerServiceDefinition;
+import io.grpc.Status;
+import io.grpc.inprocess.InProcessChannelBuilder;
+import io.grpc.inprocess.InProcessServerBuilder;
+import io.grpc.protobuf.ProtoUtils;
+import io.grpc.stub.ServerCalls;
+import io.grpc.stub.StreamObserver;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.PeriodTaskScheduler;
+import org.apache.camel.support.DefaultContextReloadStrategy;
+import org.apache.camel.support.PluginHelper;
+import org.apache.camel.support.TimerListenerManager;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
+/**
+ * A Google Pub/Sub subscriber that fails (here on a PERMISSION_DENIED of its 
streaming pull) does not end the GCP
+ * secret refresh: the next refresh starts a new subscriber, which receives 
the next secret event. The real Subscriber
+ * runs against an in-process fake of the Pub/Sub Subscriber service.
+ */
+class PubsubReloadTriggerTaskSubscriberFailedTest {
+
+    private static final String SERVICE = "google.pubsub.v1.Subscriber";
+    private static final MethodDescriptor<StreamingPullRequest, 
StreamingPullResponse> STREAMING_PULL
+            = MethodDescriptor.<StreamingPullRequest, StreamingPullResponse> 
newBuilder()
+                    .setType(MethodDescriptor.MethodType.BIDI_STREAMING)
+                    
.setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE, 
"StreamingPull"))
+                    
.setRequestMarshaller(ProtoUtils.marshaller(StreamingPullRequest.getDefaultInstance()))
+                    
.setResponseMarshaller(ProtoUtils.marshaller(StreamingPullResponse.getDefaultInstance()))
+                    .build();
+    private static final MethodDescriptor<AcknowledgeRequest, Empty> 
ACKNOWLEDGE
+            = MethodDescriptor.<AcknowledgeRequest, Empty> newBuilder()
+                    .setType(MethodDescriptor.MethodType.UNARY)
+                    
.setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE, 
"Acknowledge"))
+                    
.setRequestMarshaller(ProtoUtils.marshaller(AcknowledgeRequest.getDefaultInstance()))
+                    
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
+                    .build();
+    private static final MethodDescriptor<ModifyAckDeadlineRequest, Empty> 
MODIFY_ACK_DEADLINE
+            = MethodDescriptor.<ModifyAckDeadlineRequest, Empty> newBuilder()
+                    .setType(MethodDescriptor.MethodType.UNARY)
+                    
.setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE, 
"ModifyAckDeadline"))
+                    
.setRequestMarshaller(ProtoUtils.marshaller(ModifyAckDeadlineRequest.getDefaultInstance()))
+                    
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
+                    .build();
+
+    @Test
+    void rotationAfterTheSubscriberFailedTriggersTheReload() throws Exception {
+        FakePubsub fake = new FakePubsub();
+        try (Harness harness = new Harness(fake, 100)) {
+            List<Subscriber> subscribers = harness.subscribers;
+            // the first refresh starts the subscriber, which fails on the 
PERMISSION_DENIED of its streaming pull
+            await().atMost(Duration.ofSeconds(10))
+                    .untilAsserted(() -> 
assertThat(subscribers.get(0).state()).isEqualTo(ApiService.State.FAILED));
+
+            // the permission is back, and the secret gets a new version
+            fake.permitted = true;
+            await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> 
assertThat(harness.reloads.get()).isEqualTo(1));
+
+            assertThat(subscribers).hasSizeGreaterThan(1);
+            assertThat(subscribers.get(subscribers.size() - 
1).state()).isEqualTo(ApiService.State.RUNNING);
+            assertThat(harness.captor.events)
+                    .anyMatch(event -> event.getLevel() == Level.WARN
+                            && 
event.getMessage().getFormattedMessage().contains("PERMISSION_DENIED"));
+            // the new subscriber is still running at the next refresh: logged 
at INFO
+            await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> 
assertThat(harness.captor.events)
+                    .anyMatch(event -> event.getLevel() == Level.INFO
+                            && 
event.getMessage().getFormattedMessage().contains("running again")));
+
+            // stopping Camel stops the subscriber that replaced the failed one
+            harness.context.stop();
+            assertThat(subscribers.get(subscribers.size() - 
1).state()).isIn(ApiService.State.STOPPING,
+                    ApiService.State.TERMINATED);
+        }
+    }
+
+    @Test
+    void streamingPullThatKeepsBeingRefusedIsLoggedAtWarnOnce() throws 
Exception {
+        FakePubsub fake = new FakePubsub();
+        // refused 50 ms after the streaming pull started, so each new 
subscriber reports RUNNING first (as over a
+        // network), and before the next refresh (500 ms later)
+        fake.refusalDelay = 50;
+        try (Harness harness = new Harness(fake, 500)) {
+            // the second subscriber is built when the first one failed: none 
has run since
+            await().atMost(Duration.ofSeconds(10)).until(() -> 
harness.subscribers.size() >= 2);
+            Instant lastCheck = harness.task.getLastCheckTime();
+
+            await().atMost(Duration.ofSeconds(30)).until(() -> 
harness.subscribers.size() >= 5);
+            assertThat(harness.task.getLastCheckTime()).isEqualTo(lastCheck);
+            assertThat(harness.captor.events).filteredOn(event -> 
event.getLevel() == Level.WARN).hasSize(1);
+            assertThat(harness.captor.events).noneMatch(event -> 
event.getLevel() == Level.INFO);
+        }
+    }
+
+    /**
+     * The task scheduled with the CamelContext's period task scheduler (the 
given refresh period, 50 ms ticks), its
+     * subscribers built against the fake Pub/Sub, and the log events of the 
task.
+     */
+    private static final class Harness implements AutoCloseable {
+        private final Server server;
+        private final List<ManagedChannel> channels = new 
CopyOnWriteArrayList<>();
+        private final List<Subscriber> subscribers = new 
CopyOnWriteArrayList<>();
+        private final AtomicInteger reloads = new AtomicInteger();
+        private final Logger logger = (Logger) 
LogManager.getLogger(PubsubReloadTriggerTask.class);
+        private final LogEventCaptor captor = new LogEventCaptor();
+        private final DefaultCamelContext context = new DefaultCamelContext();
+        private final PubsubReloadTriggerTask task;
+
+        Harness(FakePubsub fake, long refreshPeriod) throws Exception {
+            String name = InProcessServerBuilder.generateName();
+            server = 
InProcessServerBuilder.forName(name).directExecutor().addService(fake.service()).build().start();
+            logger.addAppender(captor);
+            context.addService(new DefaultContextReloadStrategy() {
+                @Override
+                public void onReload(Object source) {
+                    reloads.incrementAndGet();
+                }
+            });
+            PeriodTaskScheduler scheduler = 
PluginHelper.getPeriodTaskScheduler(context);
+            ((TimerListenerManager) scheduler).setInterval(50);
+            context.start();
+
+            task = new PubsubReloadTriggerTask() {
+                @Override
+                protected void doStart() throws Exception {
+                    // what doStart sets up, without GCP credentials: the 
watched secrets, and a subscriber factory that
+                    // builds subscribers with the receiver of the task, here 
against the fake Pub/Sub
+                    setField(this, "secrets", "database-password");
+                    subscriberFactory = () -> {
+                        ManagedChannel channel = 
InProcessChannelBuilder.forName(name).directExecutor().build();
+                        channels.add(channel);
+                        Subscriber subscriber = Subscriber
+                                .newBuilder(ProjectSubscriptionName.of("p", 
"secret-events"),
+                                        new FilteringEventMessageReceiver())
+                                .setChannelProvider(
+                                        
FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)))
+                                
.setCredentialsProvider(NoCredentialsProvider.create())
+                                .build();
+                        subscribers.add(subscriber);
+                        return subscriber;
+                    };
+                    setField(this, "subscriber", subscriberFactory.get());
+                }
+            };
+            // as DefaultConfigurationConfigurer schedules it 
(gcp().getRefreshPeriod())
+            scheduler.schedulePeriodTask(task, refreshPeriod);
+        }
+
+        @Override
+        public void close() {
+            logger.removeAppender(captor);
+            context.stop();
+            channels.forEach(ManagedChannel::shutdownNow);
+            server.shutdownNow();
+        }
+    }
+
+    private static void setField(Object target, String name, Object value) 
throws Exception {
+        Field f = PubsubReloadTriggerTask.class.getDeclaredField(name);
+        f.setAccessible(true);
+        f.set(target, value);
+    }
+
+    /**
+     * The fake Pub/Sub: answers a streaming pull with PERMISSION_DENIED (a 
status that the Subscriber does not retry:
+     * it goes to FAILED), at once or after a delay, until permitted, then 
delivers one event of a new version of the
+     * watched secret, once.
+     */
+    private static final class FakePubsub {
+        private volatile boolean permitted;
+        // how long after the streaming pull starts it is refused (0: at once)
+        private volatile long refusalDelay;
+        private final AtomicBoolean delivered = new AtomicBoolean();
+
+        ServerServiceDefinition service() {
+            return ServerServiceDefinition.builder(SERVICE)
+                    .addMethod(STREAMING_PULL, 
ServerCalls.asyncBidiStreamingCall(this::streamingPull))
+                    .addMethod(ACKNOWLEDGE, 
ServerCalls.asyncUnaryCall((AcknowledgeRequest req, StreamObserver<Empty> o) -> 
{
+                        o.onNext(Empty.getDefaultInstance());
+                        o.onCompleted();
+                    }))
+                    .addMethod(MODIFY_ACK_DEADLINE,
+                            
ServerCalls.asyncUnaryCall((ModifyAckDeadlineRequest req, StreamObserver<Empty> 
o) -> {
+                                o.onNext(Empty.getDefaultInstance());
+                                o.onCompleted();
+                            }))
+                    .build();
+        }
+
+        private StreamObserver<StreamingPullRequest> 
streamingPull(StreamObserver<StreamingPullResponse> responses) {
+            return new StreamObserver<>() {
+                private boolean first = true;
+
+                @Override
+                public void onNext(StreamingPullRequest request) {
+                    if (!first) {
+                        // acks and ack deadline changes sent on the stream
+                        return;
+                    }
+                    first = false;
+                    if (!permitted) {
+                        Runnable refuse = () -> 
responses.onError(Status.PERMISSION_DENIED
+                                .withDescription("User not authorized to 
perform this action.").asRuntimeException());
+                        if (refusalDelay > 0) {
+                            CompletableFuture.delayedExecutor(refusalDelay, 
TimeUnit.MILLISECONDS).execute(refuse);
+                        } else {
+                            refuse.run();
+                        }
+                        return;
+                    }
+                    if (!delivered.compareAndSet(false, true)) {
+                        return;
+                    }
+                    PubsubMessage message = PubsubMessage.newBuilder()
+                            .putAttributes("eventType", "SECRET_VERSION_ADD")
+                            .putAttributes("secretId", 
"projects/p/secrets/database-password")
+                            .setMessageId("1")
+                            
.setPublishTime(Timestamp.newBuilder().setSeconds(Instant.now().getEpochSecond()))
+                            .build();
+                    responses.onNext(StreamingPullResponse.newBuilder()
+                            
.addReceivedMessages(ReceivedMessage.newBuilder().setAckId("ack-1").setMessage(message))
+                            .build());
+                }
+
+                @Override
+                public void onError(Throwable t) {
+                    // the subscriber closed its stream
+                }
+
+                @Override
+                public void onCompleted() {
+                    responses.onCompleted();
+                }
+            };
+        }
+    }
+
+    private static final class LogEventCaptor extends AbstractAppender {
+        private final List<LogEvent> events = new CopyOnWriteArrayList<>();
+
+        LogEventCaptor() {
+            super("PubsubReloadTriggerTaskCaptor", null, null, false, 
Property.EMPTY_ARRAY);
+            start();
+        }
+
+        @Override
+        public void append(LogEvent event) {
+            events.add(event.toImmutable());
+        }
+    }
+}

Reply via email to