|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import threading |
| 4 | +import time |
| 5 | +import typing |
| 6 | + |
| 7 | +import grpc |
| 8 | + |
| 9 | +from openfeature.evaluation_context import EvaluationContext |
| 10 | +from openfeature.event import ProviderEventDetails |
| 11 | +from openfeature.exception import ErrorCode, ParseError, ProviderNotReadyError |
| 12 | +from openfeature.schemas.protobuf.flagd.sync.v1 import ( |
| 13 | + sync_pb2, |
| 14 | + sync_pb2_grpc, |
| 15 | +) |
| 16 | + |
| 17 | +from ....config import Config |
| 18 | +from ..connector import FlagStateConnector |
| 19 | +from ..flags import FlagStore |
| 20 | + |
| 21 | +logger = logging.getLogger("openfeature.contrib") |
| 22 | + |
| 23 | + |
| 24 | +class GrpcWatcher(FlagStateConnector): |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + config: Config, |
| 28 | + flag_store: FlagStore, |
| 29 | + emit_provider_ready: typing.Callable[[ProviderEventDetails], None], |
| 30 | + emit_provider_error: typing.Callable[[ProviderEventDetails], None], |
| 31 | + emit_provider_stale: typing.Callable[[ProviderEventDetails], None], |
| 32 | + ): |
| 33 | + self.flag_store = flag_store |
| 34 | + self.config = config |
| 35 | + |
| 36 | + self.channel = self._generate_channel(config) |
| 37 | + self.stub = sync_pb2_grpc.FlagSyncServiceStub(self.channel) |
| 38 | + self.retry_backoff_seconds = config.retry_backoff_ms * 0.001 |
| 39 | + self.retry_backoff_max_seconds = config.retry_backoff_ms * 0.001 |
| 40 | + self.retry_grace_period = config.retry_grace_period |
| 41 | + self.streamline_deadline_seconds = config.stream_deadline_ms * 0.001 |
| 42 | + self.deadline = config.deadline_ms * 0.001 |
| 43 | + self.selector = config.selector |
| 44 | + self.emit_provider_ready = emit_provider_ready |
| 45 | + self.emit_provider_error = emit_provider_error |
| 46 | + self.emit_provider_stale = emit_provider_stale |
| 47 | + |
| 48 | + self.connected = False |
| 49 | + self.thread: typing.Optional[threading.Thread] = None |
| 50 | + self.timer: typing.Optional[threading.Timer] = None |
| 51 | + |
| 52 | + self.start_time = time.time() |
| 53 | + |
| 54 | + def _generate_channel(self, config: Config) -> grpc.Channel: |
| 55 | + target = f"{config.host}:{config.port}" |
| 56 | + # Create the channel with the service config |
| 57 | + options = [ |
| 58 | + ("grpc.keepalive_time_ms", config.keep_alive_time), |
| 59 | + ("grpc.initial_reconnect_backoff_ms", config.retry_backoff_ms), |
| 60 | + ("grpc.max_reconnect_backoff_ms", config.retry_backoff_max_ms), |
| 61 | + ("grpc.min_reconnect_backoff_ms", config.stream_deadline_ms), |
| 62 | + ] |
| 63 | + if config.tls: |
| 64 | + channel_args = { |
| 65 | + "options": options, |
| 66 | + "credentials": grpc.ssl_channel_credentials(), |
| 67 | + } |
| 68 | + if config.cert_path: |
| 69 | + with open(config.cert_path, "rb") as f: |
| 70 | + channel_args["credentials"] = grpc.ssl_channel_credentials(f.read()) |
| 71 | + |
| 72 | + channel = grpc.secure_channel(target, **channel_args) |
| 73 | + |
| 74 | + else: |
| 75 | + channel = grpc.insecure_channel( |
| 76 | + target, |
| 77 | + options=options, |
| 78 | + ) |
| 79 | + |
| 80 | + return channel |
| 81 | + |
| 82 | + def initialize(self, context: EvaluationContext) -> None: |
| 83 | + self.connect() |
| 84 | + |
| 85 | + def connect(self) -> None: |
| 86 | + self.active = True |
| 87 | + |
| 88 | + # Run monitoring in a separate thread |
| 89 | + self.monitor_thread = threading.Thread( |
| 90 | + target=self.monitor, daemon=True, name="FlagdGrpcSyncServiceMonitorThread" |
| 91 | + ) |
| 92 | + self.monitor_thread.start() |
| 93 | + ## block until ready or deadline reached |
| 94 | + timeout = self.deadline + time.time() |
| 95 | + while not self.connected and time.time() < timeout: |
| 96 | + time.sleep(0.05) |
| 97 | + logger.debug("Finished blocking gRPC state initialization") |
| 98 | + |
| 99 | + if not self.connected: |
| 100 | + raise ProviderNotReadyError( |
| 101 | + "Blocking init finished before data synced. Consider increasing startup deadline to avoid inconsistent evaluations." |
| 102 | + ) |
| 103 | + |
| 104 | + def monitor(self) -> None: |
| 105 | + self.channel.subscribe(self._state_change_callback, try_to_connect=True) |
| 106 | + |
| 107 | + def _state_change_callback(self, new_state: grpc.ChannelConnectivity) -> None: |
| 108 | + logger.debug(f"gRPC state change: {new_state}") |
| 109 | + if new_state == grpc.ChannelConnectivity.READY: |
| 110 | + if not self.thread or not self.thread.is_alive(): |
| 111 | + self.thread = threading.Thread( |
| 112 | + target=self.listen, |
| 113 | + daemon=True, |
| 114 | + name="FlagdGrpcSyncWorkerThread", |
| 115 | + ) |
| 116 | + self.thread.start() |
| 117 | + |
| 118 | + if self.timer and self.timer.is_alive(): |
| 119 | + logger.debug("gRPC error timer expired") |
| 120 | + self.timer.cancel() |
| 121 | + |
| 122 | + elif new_state == grpc.ChannelConnectivity.TRANSIENT_FAILURE: |
| 123 | + # this is the failed reconnect attempt so we are going into stale |
| 124 | + self.emit_provider_stale( |
| 125 | + ProviderEventDetails( |
| 126 | + message="gRPC sync disconnected, reconnecting", |
| 127 | + ) |
| 128 | + ) |
| 129 | + self.start_time = time.time() |
| 130 | + # adding a timer, so we can emit the error event after time |
| 131 | + self.timer = threading.Timer(self.retry_grace_period, self.emit_error) |
| 132 | + |
| 133 | + logger.debug("gRPC error timer started") |
| 134 | + self.timer.start() |
| 135 | + self.connected = False |
| 136 | + |
| 137 | + def emit_error(self) -> None: |
| 138 | + logger.debug("gRPC error emitted") |
| 139 | + self.emit_provider_error( |
| 140 | + ProviderEventDetails( |
| 141 | + message="gRPC sync disconnected, reconnecting", |
| 142 | + error_code=ErrorCode.GENERAL, |
| 143 | + ) |
| 144 | + ) |
| 145 | + |
| 146 | + def shutdown(self) -> None: |
| 147 | + self.active = False |
| 148 | + self.channel.close() |
| 149 | + |
| 150 | + def listen(self) -> None: |
| 151 | + call_args = ( |
| 152 | + {"timeout": self.streamline_deadline_seconds} |
| 153 | + if self.streamline_deadline_seconds > 0 |
| 154 | + else {} |
| 155 | + ) |
| 156 | + request_args = {"selector": self.selector} if self.selector is not None else {} |
| 157 | + |
| 158 | + while self.active: |
| 159 | + try: |
| 160 | + request = sync_pb2.SyncFlagsRequest(**request_args) |
| 161 | + |
| 162 | + logger.debug("Setting up gRPC sync flags connection") |
| 163 | + for flag_rsp in self.stub.SyncFlags( |
| 164 | + request, wait_for_ready=True, **call_args |
| 165 | + ): |
| 166 | + flag_str = flag_rsp.flag_configuration |
| 167 | + logger.debug( |
| 168 | + f"Received flag configuration - {abs(hash(flag_str)) % (10**8)}" |
| 169 | + ) |
| 170 | + self.flag_store.update(json.loads(flag_str)) |
| 171 | + |
| 172 | + if not self.connected: |
| 173 | + self.emit_provider_ready( |
| 174 | + ProviderEventDetails( |
| 175 | + message="gRPC sync connection established" |
| 176 | + ) |
| 177 | + ) |
| 178 | + self.connected = True |
| 179 | + |
| 180 | + if not self.active: |
| 181 | + logger.debug("Terminating gRPC sync thread") |
| 182 | + return |
| 183 | + except grpc.RpcError as e: # noqa: PERF203 |
| 184 | + logger.error(f"SyncFlags stream error, {e.code()=} {e.details()=}") |
| 185 | + except json.JSONDecodeError: |
| 186 | + logger.exception( |
| 187 | + f"Could not parse JSON flag data from SyncFlags endpoint: {flag_str=}" |
| 188 | + ) |
| 189 | + except ParseError: |
| 190 | + logger.exception( |
| 191 | + f"Could not parse flag data using flagd syntax: {flag_str=}" |
| 192 | + ) |
0 commit comments