|
| 1 | +package dev.openfeature.contrib.providers.flagd.resolver.common; |
| 2 | + |
| 3 | +import dev.openfeature.sdk.exceptions.GeneralError; |
| 4 | +import io.grpc.ConnectivityState; |
| 5 | +import io.grpc.ManagedChannel; |
| 6 | +import lombok.extern.slf4j.Slf4j; |
| 7 | + |
| 8 | +import java.util.concurrent.CountDownLatch; |
| 9 | +import java.util.concurrent.ScheduledExecutorService; |
| 10 | +import java.util.concurrent.ScheduledFuture; |
| 11 | +import java.util.concurrent.TimeUnit; |
| 12 | +import java.util.concurrent.atomic.AtomicReference; |
| 13 | + |
| 14 | + |
| 15 | +/** |
| 16 | + * A utility class to monitor and manage the connectivity state of a gRPC ManagedChannel. |
| 17 | + */ |
| 18 | +@Slf4j |
| 19 | +public class ChannelMonitor { |
| 20 | + |
| 21 | + |
| 22 | + private ChannelMonitor() { |
| 23 | + |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Monitors the state of a gRPC channel and triggers the specified callbacks based on state changes. |
| 28 | + * |
| 29 | + * @param expectedState the initial state to monitor. |
| 30 | + * @param channel the ManagedChannel to monitor. |
| 31 | + * @param onConnectionReady callback invoked when the channel transitions to a READY state. |
| 32 | + * @param onConnectionLost callback invoked when the channel transitions to a FAILURE or SHUTDOWN state. |
| 33 | + */ |
| 34 | + public static void monitorChannelState(ConnectivityState expectedState, ManagedChannel channel, |
| 35 | + Runnable onConnectionReady, Runnable onConnectionLost) { |
| 36 | + channel.notifyWhenStateChanged(expectedState, () -> { |
| 37 | + ConnectivityState currentState = channel.getState(true); |
| 38 | + log.info("Channel state changed to: {}", currentState); |
| 39 | + if (currentState == ConnectivityState.READY) { |
| 40 | + onConnectionReady.run(); |
| 41 | + } else if (currentState == ConnectivityState.TRANSIENT_FAILURE |
| 42 | + || currentState == ConnectivityState.SHUTDOWN) { |
| 43 | + onConnectionLost.run(); |
| 44 | + } |
| 45 | + // Re-register the state monitor to watch for the next state transition. |
| 46 | + monitorChannelState(currentState, channel, onConnectionReady, onConnectionLost); |
| 47 | + }); |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + /** |
| 52 | + * Waits for the channel to reach a desired state within a specified timeout period. |
| 53 | + * |
| 54 | + * @param channel the ManagedChannel to monitor. |
| 55 | + * @param desiredState the ConnectivityState to wait for. |
| 56 | + * @param connectCallback callback invoked when the desired state is reached. |
| 57 | + * @param timeout the maximum amount of time to wait. |
| 58 | + * @param unit the time unit of the timeout. |
| 59 | + * @throws InterruptedException if the current thread is interrupted while waiting. |
| 60 | + */ |
| 61 | + public static void waitForDesiredState(ManagedChannel channel, |
| 62 | + ConnectivityState desiredState, |
| 63 | + Runnable connectCallback, |
| 64 | + long timeout, |
| 65 | + TimeUnit unit) throws InterruptedException { |
| 66 | + waitForDesiredState(channel, desiredState, connectCallback, new CountDownLatch(1), timeout, unit); |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | + private static void waitForDesiredState(ManagedChannel channel, |
| 71 | + ConnectivityState desiredState, |
| 72 | + Runnable connectCallback, |
| 73 | + CountDownLatch latch, |
| 74 | + long timeout, |
| 75 | + TimeUnit unit) throws InterruptedException { |
| 76 | + channel.notifyWhenStateChanged(ConnectivityState.SHUTDOWN, () -> { |
| 77 | + try { |
| 78 | + ConnectivityState state = channel.getState(true); |
| 79 | + log.debug("Channel state changed to: {}", state); |
| 80 | + |
| 81 | + if (state == desiredState) { |
| 82 | + connectCallback.run(); |
| 83 | + latch.countDown(); |
| 84 | + return; |
| 85 | + } |
| 86 | + waitForDesiredState(channel, desiredState, connectCallback, latch, timeout, unit); |
| 87 | + } catch (InterruptedException e) { |
| 88 | + Thread.currentThread().interrupt(); |
| 89 | + log.error("Thread interrupted while waiting for desired state", e); |
| 90 | + } catch (Exception e) { |
| 91 | + log.error("Error occurred while waiting for desired state", e); |
| 92 | + } |
| 93 | + }); |
| 94 | + |
| 95 | + // Await the latch or timeout for the state change |
| 96 | + if (!latch.await(timeout, unit)) { |
| 97 | + throw new GeneralError(String.format("Deadline exceeded. Condition did not complete within the %d " |
| 98 | + + "deadline", timeout)); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | + /** |
| 104 | + * Polls the state of a gRPC channel at regular intervals and triggers callbacks upon state changes. |
| 105 | + * |
| 106 | + * @param executor the ScheduledExecutorService used for polling. |
| 107 | + * @param channel the ManagedChannel to monitor. |
| 108 | + * @param onConnectionReady callback invoked when the channel transitions to a READY state. |
| 109 | + * @param onConnectionLost callback invoked when the channel transitions to a FAILURE or SHUTDOWN state. |
| 110 | + * @param pollIntervalMs the polling interval in milliseconds. |
| 111 | + */ |
| 112 | + public static void pollChannelState(ScheduledExecutorService executor, ManagedChannel channel, |
| 113 | + Runnable onConnectionReady, |
| 114 | + Runnable onConnectionLost, long pollIntervalMs) { |
| 115 | + |
| 116 | + AtomicReference<ConnectivityState> lastState = new AtomicReference<>(ConnectivityState.READY); |
| 117 | + |
| 118 | + Runnable pollTask = () -> { |
| 119 | + ConnectivityState currentState = channel.getState(true); |
| 120 | + if (currentState != lastState.get()) { |
| 121 | + if (currentState == ConnectivityState.READY) { |
| 122 | + log.debug("gRPC connection became READY"); |
| 123 | + onConnectionReady.run(); |
| 124 | + } else if (currentState == ConnectivityState.TRANSIENT_FAILURE |
| 125 | + || currentState == ConnectivityState.SHUTDOWN) { |
| 126 | + log.debug("gRPC connection became TRANSIENT_FAILURE"); |
| 127 | + onConnectionLost.run(); |
| 128 | + } |
| 129 | + lastState.set(currentState); |
| 130 | + } |
| 131 | + }; |
| 132 | + executor.scheduleAtFixedRate(pollTask, 0, pollIntervalMs, TimeUnit.MILLISECONDS); |
| 133 | + } |
| 134 | + |
| 135 | + |
| 136 | + /** |
| 137 | + * Polls the channel state at fixed intervals and waits for the channel to reach a desired state within a timeout |
| 138 | + * period. |
| 139 | + * |
| 140 | + * @param executor the ScheduledExecutorService used for polling. |
| 141 | + * @param channel the ManagedChannel to monitor. |
| 142 | + * @param desiredState the ConnectivityState to wait for. |
| 143 | + * @param connectCallback callback invoked when the desired state is reached. |
| 144 | + * @param timeout the maximum amount of time to wait. |
| 145 | + * @param unit the time unit of the timeout. |
| 146 | + * @return {@code true} if the desired state was reached within the timeout period, {@code false} otherwise. |
| 147 | + * @throws InterruptedException if the current thread is interrupted while waiting. |
| 148 | + */ |
| 149 | + public static boolean pollForDesiredState(ScheduledExecutorService executor, ManagedChannel channel, |
| 150 | + ConnectivityState desiredState, Runnable connectCallback, long timeout, |
| 151 | + TimeUnit unit) throws InterruptedException { |
| 152 | + CountDownLatch latch = new CountDownLatch(1); |
| 153 | + |
| 154 | + Runnable waitForStateTask = () -> { |
| 155 | + ConnectivityState currentState = channel.getState(true); |
| 156 | + if (currentState == desiredState) { |
| 157 | + connectCallback.run(); |
| 158 | + latch.countDown(); |
| 159 | + } |
| 160 | + }; |
| 161 | + |
| 162 | + ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(waitForStateTask, 0, 100, |
| 163 | + TimeUnit.MILLISECONDS); |
| 164 | + |
| 165 | + boolean success = latch.await(timeout, unit); |
| 166 | + scheduledFuture.cancel(true); |
| 167 | + return success; |
| 168 | + } |
| 169 | +} |
0 commit comments