|
| 1 | +import threading |
| 2 | +import time |
| 3 | +import requests |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from concurrent.futures import ThreadPoolExecutor |
| 6 | +from typing import Dict, Optional, List, Any, TYPE_CHECKING |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from databricks.sql.client import Connection |
| 10 | + |
| 11 | + |
| 12 | +@dataclass |
| 13 | +class FeatureFlagEntry: |
| 14 | + """Represents a single feature flag from the server response.""" |
| 15 | + |
| 16 | + name: str |
| 17 | + value: str |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class FeatureFlagsResponse: |
| 22 | + """Represents the full JSON response from the feature flag endpoint.""" |
| 23 | + |
| 24 | + flags: List[FeatureFlagEntry] = field(default_factory=list) |
| 25 | + ttl_seconds: Optional[int] = None |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def from_dict(cls, data: Dict[str, Any]) -> "FeatureFlagsResponse": |
| 29 | + """Factory method to create an instance from a dictionary (parsed JSON).""" |
| 30 | + flags_data = data.get("flags", []) |
| 31 | + flags_list = [FeatureFlagEntry(**flag) for flag in flags_data] |
| 32 | + return cls(flags=flags_list, ttl_seconds=data.get("ttl_seconds")) |
| 33 | + |
| 34 | + |
| 35 | +# --- Constants --- |
| 36 | +FEATURE_FLAGS_ENDPOINT_SUFFIX_FORMAT = ( |
| 37 | + "/api/2.0/connector-service/feature-flags/PYTHON/{}" |
| 38 | +) |
| 39 | +DEFAULT_TTL_SECONDS = 900 # 15 minutes |
| 40 | +REFRESH_BEFORE_EXPIRY_SECONDS = 10 # Start proactive refresh 10s before expiry |
| 41 | + |
| 42 | + |
| 43 | +class FeatureFlagsContext: |
| 44 | + """ |
| 45 | + Manages fetching and caching of server-side feature flags for a connection. |
| 46 | +
|
| 47 | + 1. The very first check for any flag is a synchronous, BLOCKING operation. |
| 48 | + 2. Subsequent refreshes (triggered near TTL expiry) are done asynchronously |
| 49 | + in the background, returning stale data until the refresh completes. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, connection: "Connection", executor: ThreadPoolExecutor): |
| 53 | + from databricks.sql import __version__ |
| 54 | + |
| 55 | + self._connection = connection |
| 56 | + self._executor = executor # Used for ASYNCHRONOUS refreshes |
| 57 | + self._lock = threading.RLock() |
| 58 | + |
| 59 | + # Cache state: `None` indicates the cache has never been loaded. |
| 60 | + self._flags: Optional[Dict[str, str]] = None |
| 61 | + self._ttl_seconds: int = DEFAULT_TTL_SECONDS |
| 62 | + self._last_refresh_time: float = 0 |
| 63 | + |
| 64 | + endpoint_suffix = FEATURE_FLAGS_ENDPOINT_SUFFIX_FORMAT.format(__version__) |
| 65 | + self._feature_flag_endpoint = ( |
| 66 | + f"https://{self._connection.session.host}{endpoint_suffix}" |
| 67 | + ) |
| 68 | + |
| 69 | + def _is_refresh_needed(self) -> bool: |
| 70 | + """Checks if the cache is due for a proactive background refresh.""" |
| 71 | + if self._flags is None: |
| 72 | + return False # Not eligible for refresh until loaded once. |
| 73 | + |
| 74 | + refresh_threshold = self._last_refresh_time + ( |
| 75 | + self._ttl_seconds - REFRESH_BEFORE_EXPIRY_SECONDS |
| 76 | + ) |
| 77 | + return time.monotonic() > refresh_threshold |
| 78 | + |
| 79 | + def get_flag_value(self, name: str, default_value: Any) -> Any: |
| 80 | + """ |
| 81 | + Checks if a feature is enabled. |
| 82 | + - BLOCKS on the first call until flags are fetched. |
| 83 | + - Returns cached values on subsequent calls, triggering non-blocking refreshes if needed. |
| 84 | + """ |
| 85 | + with self._lock: |
| 86 | + # If cache has never been loaded, perform a synchronous, blocking fetch. |
| 87 | + if self._flags is None: |
| 88 | + self._refresh_flags() |
| 89 | + |
| 90 | + # If a proactive background refresh is needed, start one. This is non-blocking. |
| 91 | + elif self._is_refresh_needed(): |
| 92 | + # We don't check for an in-flight refresh; the executor queues the task, which is safe. |
| 93 | + self._executor.submit(self._refresh_flags) |
| 94 | + |
| 95 | + assert self._flags is not None |
| 96 | + |
| 97 | + # Now, return the value from the populated cache. |
| 98 | + return self._flags.get(name, default_value) |
| 99 | + |
| 100 | + def _refresh_flags(self): |
| 101 | + """Performs a synchronous network request to fetch and update flags.""" |
| 102 | + headers = {} |
| 103 | + try: |
| 104 | + # Authenticate the request |
| 105 | + self._connection.session.auth_provider.add_headers(headers) |
| 106 | + headers["User-Agent"] = self._connection.session.useragent_header |
| 107 | + |
| 108 | + response = requests.get( |
| 109 | + self._feature_flag_endpoint, headers=headers, timeout=30 |
| 110 | + ) |
| 111 | + |
| 112 | + if response.status_code == 200: |
| 113 | + ff_response = FeatureFlagsResponse.from_dict(response.json()) |
| 114 | + self._update_cache_from_response(ff_response) |
| 115 | + else: |
| 116 | + # On failure, initialize with an empty dictionary to prevent re-blocking. |
| 117 | + if self._flags is None: |
| 118 | + self._flags = {} |
| 119 | + |
| 120 | + except Exception as e: |
| 121 | + # On exception, initialize with an empty dictionary to prevent re-blocking. |
| 122 | + if self._flags is None: |
| 123 | + self._flags = {} |
| 124 | + |
| 125 | + def _update_cache_from_response(self, ff_response: FeatureFlagsResponse): |
| 126 | + """Atomically updates the internal cache state from a successful server response.""" |
| 127 | + with self._lock: |
| 128 | + self._flags = {flag.name: flag.value for flag in ff_response.flags} |
| 129 | + if ff_response.ttl_seconds is not None and ff_response.ttl_seconds > 0: |
| 130 | + self._ttl_seconds = ff_response.ttl_seconds |
| 131 | + self._last_refresh_time = time.monotonic() |
| 132 | + |
| 133 | + |
| 134 | +class FeatureFlagsContextFactory: |
| 135 | + """ |
| 136 | + Manages a singleton instance of FeatureFlagsContext per connection session. |
| 137 | + Also manages a shared ThreadPoolExecutor for all background refresh operations. |
| 138 | + """ |
| 139 | + |
| 140 | + _context_map: Dict[str, FeatureFlagsContext] = {} |
| 141 | + _executor: Optional[ThreadPoolExecutor] = None |
| 142 | + _lock = threading.Lock() |
| 143 | + |
| 144 | + @classmethod |
| 145 | + def _initialize(cls): |
| 146 | + """Initializes the shared executor for async refreshes if it doesn't exist.""" |
| 147 | + if cls._executor is None: |
| 148 | + cls._executor = ThreadPoolExecutor( |
| 149 | + max_workers=3, thread_name_prefix="feature-flag-refresher" |
| 150 | + ) |
| 151 | + |
| 152 | + @classmethod |
| 153 | + def get_instance(cls, connection: "Connection") -> FeatureFlagsContext: |
| 154 | + """Gets or creates a FeatureFlagsContext for the given connection.""" |
| 155 | + with cls._lock: |
| 156 | + cls._initialize() |
| 157 | + assert cls._executor is not None |
| 158 | + |
| 159 | + # Use the unique session ID as the key |
| 160 | + key = connection.get_session_id_hex() |
| 161 | + if key not in cls._context_map: |
| 162 | + cls._context_map[key] = FeatureFlagsContext(connection, cls._executor) |
| 163 | + return cls._context_map[key] |
| 164 | + |
| 165 | + @classmethod |
| 166 | + def remove_instance(cls, connection: "Connection"): |
| 167 | + """Removes the context for a given connection and shuts down the executor if no clients remain.""" |
| 168 | + with cls._lock: |
| 169 | + key = connection.get_session_id_hex() |
| 170 | + if key in cls._context_map: |
| 171 | + cls._context_map.pop(key, None) |
| 172 | + |
| 173 | + # If this was the last active context, clean up the thread pool. |
| 174 | + if not cls._context_map and cls._executor is not None: |
| 175 | + cls._executor.shutdown(wait=False) |
| 176 | + cls._executor = None |
0 commit comments