|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import threading |
| 5 | +import time |
| 6 | +import typing |
| 7 | + |
| 8 | +import yaml |
| 9 | + |
| 10 | +from openfeature.contrib.provider.flagd.config import Config |
| 11 | +from openfeature.contrib.provider.flagd.resolvers.process.connector import ( |
| 12 | + FlagStateConnector, |
| 13 | +) |
| 14 | +from openfeature.contrib.provider.flagd.resolvers.process.flags import FlagStore |
| 15 | +from openfeature.evaluation_context import EvaluationContext |
| 16 | +from openfeature.event import ProviderEventDetails |
| 17 | +from openfeature.exception import ParseError, ProviderNotReadyError |
| 18 | + |
| 19 | +logger = logging.getLogger("openfeature.contrib") |
| 20 | + |
| 21 | + |
| 22 | +class FileWatcher(FlagStateConnector): |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + config: Config, |
| 26 | + flag_store: FlagStore, |
| 27 | + emit_provider_ready: typing.Callable[[ProviderEventDetails], None], |
| 28 | + emit_provider_error: typing.Callable[[ProviderEventDetails], None], |
| 29 | + ): |
| 30 | + if config.offline_flag_source_path is None: |
| 31 | + raise ValueError( |
| 32 | + f"`config.offline_flag_source_path` parameter invalid: {config.offline_flag_source_path}" |
| 33 | + ) |
| 34 | + else: |
| 35 | + self.file_path = config.offline_flag_source_path |
| 36 | + |
| 37 | + self.emit_provider_ready = emit_provider_ready |
| 38 | + self.emit_provider_error = emit_provider_error |
| 39 | + self.deadline_seconds = config.deadline_ms * 0.001 |
| 40 | + |
| 41 | + self.last_modified = 0.0 |
| 42 | + self.flag_store = flag_store |
| 43 | + self.should_emit_ready_on_success = False |
| 44 | + |
| 45 | + def initialize(self, evaluation_context: EvaluationContext) -> None: |
| 46 | + self.active = True |
| 47 | + self.thread = threading.Thread( |
| 48 | + target=self.refresh_file, daemon=True, name="FlagdFileWatcherWorkerThread" |
| 49 | + ) |
| 50 | + self.thread.start() |
| 51 | + |
| 52 | + # Let this throw exceptions so that provider status is set correctly |
| 53 | + try: |
| 54 | + self.should_emit_ready_on_success = True |
| 55 | + self._load_data() |
| 56 | + except Exception as err: |
| 57 | + raise ProviderNotReadyError from err |
| 58 | + |
| 59 | + def shutdown(self) -> None: |
| 60 | + self.active = False |
| 61 | + |
| 62 | + def refresh_file(self) -> None: |
| 63 | + while self.active: |
| 64 | + time.sleep(self.deadline_seconds) |
| 65 | + logger.debug("checking for new flag store contents from file") |
| 66 | + self.safe_load_data() |
| 67 | + |
| 68 | + def safe_load_data(self) -> None: |
| 69 | + try: |
| 70 | + last_modified = os.path.getmtime(self.file_path) |
| 71 | + if last_modified > self.last_modified: |
| 72 | + self._load_data(last_modified) |
| 73 | + except FileNotFoundError: |
| 74 | + self.handle_error("Provided file path not valid") |
| 75 | + except json.JSONDecodeError: |
| 76 | + self.handle_error("Could not parse JSON flag data from file") |
| 77 | + except yaml.error.YAMLError: |
| 78 | + self.handle_error("Could not parse YAML flag data from file") |
| 79 | + except ParseError: |
| 80 | + self.handle_error("Could not parse flag data using flagd syntax") |
| 81 | + except Exception: |
| 82 | + self.handle_error("Could not read flags from file") |
| 83 | + |
| 84 | + def _load_data(self, modified_time: typing.Optional[float] = None) -> None: |
| 85 | + with open(self.file_path) as file: |
| 86 | + if self.file_path.endswith(".yaml"): |
| 87 | + data = yaml.safe_load(file) |
| 88 | + else: |
| 89 | + data = json.load(file) |
| 90 | + |
| 91 | + self.flag_store.update(data) |
| 92 | + |
| 93 | + if self.should_emit_ready_on_success: |
| 94 | + self.emit_provider_ready( |
| 95 | + ProviderEventDetails( |
| 96 | + message="Reloading file contents recovered from error state" |
| 97 | + ) |
| 98 | + ) |
| 99 | + self.should_emit_ready_on_success = False |
| 100 | + |
| 101 | + self.last_modified = modified_time or os.path.getmtime(self.file_path) |
| 102 | + |
| 103 | + def handle_error(self, error_message: str) -> None: |
| 104 | + logger.exception(error_message) |
| 105 | + self.should_emit_ready_on_success = True |
| 106 | + self.emit_provider_error(ProviderEventDetails(message=error_message)) |
0 commit comments