Repository navigation
feat: poll manifest changes and shutdown cleanly #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,38 +1,168 @@ | ||
| import logging | ||
| import threading | ||
| from datetime import timedelta | ||
|
|
||
| from octopus_openfeature_provider._feature_flag_api_client import FeatureFlagApiClient | ||
| from octopus_openfeature_provider._feature_flag_api_client import ( | ||
| ContentHashCheckError, | ||
| FeatureFlagApiClient, | ||
| ) | ||
| from octopus_openfeature_provider._feature_flag_evaluator import FeatureFlagEvaluator | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
| POLLING_THREAD_NAME = "octopus-openfeature-provider-polling" | ||
|
|
||
| _INITIAL_FETCH_FAILED = "Failed to retrieve feature manifest during initialization. Falling back to no evaluations, defaults will be used during evaluation." | ||
| _REFRESH_FAILED = ( | ||
| "Failed to retrieve updated feature manifest. Retaining the existing evaluations." | ||
| ) | ||
| _FETCH_WITHOUT_MANIFEST_FAILED = "Failed to retrieve feature manifest. No evaluations have been retrieved yet, defaults will be used during evaluation." | ||
|
|
||
|
|
||
| class FeatureFlagEvaluatorCache: | ||
| """Holds the evaluator the provider resolves flags against. | ||
| """Holds the evaluator the provider resolves flags against, and keeps it | ||
| updated by polling the feature flags service. | ||
|
|
||
| Until a fetch succeeds it holds an empty evaluator, so every flag is | ||
| missing. | ||
| missing. A failed refresh keeps the last good evaluator. | ||
| """ | ||
|
|
||
| def __init__(self, client: FeatureFlagApiClient) -> None: | ||
| self._client = client | ||
| def __init__( | ||
| self, api_client: FeatureFlagApiClient, poll_interval: timedelta | ||
| ) -> None: | ||
| self._api_client = api_client | ||
| self._poll_interval_seconds = poll_interval.total_seconds() | ||
| self._evaluator = FeatureFlagEvaluator.empty() | ||
|
|
||
| # The SDK may call initialize and shutdown on different threads, | ||
| # while the polling thread runs. The lock stops them from interfering. | ||
| # Reads of _evaluator don't need this lock. | ||
| self._lock = threading.Lock() | ||
| # Set to stop the work that initialize call started: its initial fetch | ||
| # and the polling after it. Each initialize call replaces it with a new | ||
| # event, so a fetch or refresh left over from an earlier call can tell | ||
| # it's been stopped, and won't install evaluations or outlive shutdown. | ||
| self._stop_requested = threading.Event() | ||
| self._polling_thread: threading.Thread | None = None | ||
|
|
||
| def get_evaluator(self) -> FeatureFlagEvaluator: | ||
| return self._evaluator | ||
|
|
||
| def initialize(self) -> None: | ||
| """Fetch the evaluations. Never raises.""" | ||
| """Fetch the evaluations and start polling. Never raises.""" | ||
| with self._lock: | ||
| previous_polling_thread = self._signal_stop() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In case the openfeature SDK call |
||
| stop_requested = threading.Event() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A new cancellation signal for each initialize |
||
| self._stop_requested = stop_requested | ||
| self._evaluator = FeatureFlagEvaluator.empty() | ||
| self._api_client.open() | ||
|
|
||
| _join_unless_current(previous_polling_thread) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. wait for the previous polling thread if there is any, so that there is alway only one daemon thread for http request, and we can make sure all the thread are cleaned up. |
||
|
|
||
| # The initial fetch runs on the polling thread too, so every request | ||
| # is made there and shutdown only has to wait for that thread before | ||
| # it closes the HTTP client. | ||
| initial_fetch_done = threading.Event() | ||
| polling_thread = threading.Thread( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🤖 Polling stops in servers that fork after the provider is set A forked child process gets only the thread that called Affected setups:
Not affected: Gunicorn with default settings, Uvicorn Suggested options:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hey @liamhughes , thanks for catching this issue. I have done some reading about it, instead of auto-fixing the issue (e.g. with Reasoning: This issue only happen if consumer sets the provider before calling However, we should resolve the problem that this fails silently, so I think we can log warning when this happens (forked process has different What do you think?
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @yangguoif, thank you for digging into this. It definitely seems like a complicated space. Given we are Logging a warning sounds great. |
||
| target=self._poll, | ||
| args=(stop_requested, initial_fetch_done), | ||
| name=POLLING_THREAD_NAME, | ||
| daemon=True, | ||
| ) | ||
| with self._lock: | ||
| if stop_requested.is_set(): | ||
| return | ||
| polling_thread.start() | ||
| self._polling_thread = polling_thread | ||
|
|
||
| initial_fetch_done.wait() | ||
|
|
||
| def shutdown(self) -> None: | ||
| """Stop polling, wait for a fetch or refresh in flight to finish, and | ||
| close the HTTP client if the provider created it.""" | ||
| with self._lock: | ||
| stop_requested = self._stop_requested | ||
| polling_thread = self._signal_stop() | ||
|
|
||
| _join_unless_current(polling_thread) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. wait for current in flight request before closing the http client, as documented. |
||
|
|
||
| with self._lock: | ||
| # If the cache was initialized again while this waited, that later | ||
| # initialize call owns the HTTP client now. | ||
| if self._stop_requested is stop_requested: | ||
| self._api_client.close() | ||
|
|
||
| def _signal_stop(self) -> threading.Thread | None: | ||
| self._stop_requested.set() | ||
| polling_thread = self._polling_thread | ||
| self._polling_thread = None | ||
| return polling_thread | ||
|
|
||
| def _poll( | ||
| self, stop_requested: threading.Event, initial_fetch_done: threading.Event | ||
| ) -> None: | ||
| try: | ||
| self._initial_fetch(stop_requested) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Initial fetch is moved to here, so that the request for initial fetching is sent in the same thread as periodic polling. |
||
| finally: | ||
| initial_fetch_done.set() | ||
|
|
||
| while not stop_requested.wait(self._poll_interval_seconds): | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Periodic polling loop here. |
||
| self._refresh(stop_requested) | ||
|
|
||
| def _initial_fetch(self, stop_requested: threading.Event) -> None: | ||
| """Never raises. A failed fetch leaves the empty evaluator.""" | ||
| try: | ||
| response = self._client.get_server_side_evaluations() | ||
| response = self._api_client.get_server_side_evaluations() | ||
| if response is None: | ||
| return | ||
| evaluator = FeatureFlagEvaluator(response) | ||
| except Exception: | ||
| _logger.exception( | ||
| "Failed to retrieve feature manifest during initialization. Falling back to no evaluations, defaults will be used during evaluation." | ||
| ) | ||
| self._evaluator = FeatureFlagEvaluator.empty() | ||
| if not stop_requested.is_set(): | ||
| _logger.exception(_INITIAL_FETCH_FAILED) | ||
| return | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because we already set the |
||
|
|
||
| self._evaluator = ( | ||
| FeatureFlagEvaluator(response) | ||
| if response is not None | ||
| else FeatureFlagEvaluator.empty() | ||
| self._install_evaluator(evaluator, stop_requested) | ||
|
|
||
| def _refresh(self, stop_requested: threading.Event) -> None: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Refresh failures log a misleading error, often with a stack trace, every poll
Could we use a different message when no manifest is held, and log
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 Nice one, thanks. I have updated the PR to tweak the log message and log |
||
| """Never raises. A failed refresh keeps the current evaluator, and the | ||
| next interval tries again.""" | ||
| current_evaluator = self._evaluator | ||
| failed_message = ( | ||
| _REFRESH_FAILED | ||
| if current_evaluator.content_hash | ||
| else _FETCH_WITHOUT_MANIFEST_FAILED | ||
| ) | ||
| try: | ||
| if not self._api_client.have_features_changed( | ||
| current_evaluator.content_hash | ||
| ): | ||
| return | ||
|
|
||
| response = self._api_client.get_server_side_evaluations() | ||
| if response is None: | ||
| _logger.error(failed_message) | ||
| return | ||
|
|
||
| evaluator = FeatureFlagEvaluator(response) | ||
| except ContentHashCheckError as error: | ||
| if not stop_requested.is_set(): | ||
| _logger.error("%s %s", failed_message, error) | ||
| return | ||
| except Exception: | ||
| if not stop_requested.is_set(): | ||
| _logger.exception(failed_message) | ||
| return | ||
|
|
||
| self._install_evaluator(evaluator, stop_requested) | ||
|
|
||
| def _install_evaluator( | ||
| self, evaluator: FeatureFlagEvaluator, stop_requested: threading.Event | ||
| ) -> None: | ||
| with self._lock: | ||
| if not stop_requested.is_set(): | ||
| self._evaluator = evaluator | ||
|
|
||
|
|
||
| def _join_unless_current(thread: threading.Thread | None) -> None: | ||
| if thread is not None and thread is not threading.current_thread(): | ||
| thread.join() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,7 +27,8 @@ class OctopusFeatureConfiguration: | |
| the response. It doesn't limit a request's total time. If | ||
| `http_client` has its own timeouts, the shorter limit applies to | ||
| each phase. Keep it well under `cache_duration` so a stalled | ||
| request can't hold up the next poll. Must be positive. | ||
| request can't hold up the next poll. Must be positive. Shutting the | ||
| provider down waits for a request in flight. | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I couldn't find a proper way to cancel the request with the current implementation. To cancel a request in flight with httpx properly, most of the researches point to Therefore updating the doc here to be more specific. |
||
| release_version_override: Overrides the application release version | ||
| embedded in `client_identifier`. It's sent to the feature flags | ||
| service only when it isn't `None`. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| import copy | ||
| import threading | ||
| from collections.abc import Mapping, Sequence | ||
| from datetime import timedelta | ||
|
|
||
|
|
@@ -16,6 +17,8 @@ | |
| OctopusFeatureConfiguration, | ||
| ) | ||
|
|
||
| MAX_CACHE_DURATION = timedelta(seconds=threading.TIMEOUT_MAX) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is a different value from the Typescript implementation, I decided to go with the constant native for Python to avoid magic number. |
||
|
|
||
|
|
||
| class OctopusFeatureProvider(AbstractProvider): | ||
| """An OpenFeature provider for Octopus feature flags. | ||
|
|
@@ -25,7 +28,8 @@ class OctopusFeatureProvider(AbstractProvider): | |
|
|
||
| Raises: | ||
| ValueError: If the configuration's client identifier is empty, or its | ||
| `cache_duration` or `request_timeout` isn't positive. | ||
| `cache_duration` or `request_timeout` isn't positive, or its | ||
| `cache_duration` is longer than `threading.TIMEOUT_MAX` seconds. | ||
| TypeError: If the configuration's client identifier isn't a `str`, | ||
| or its `cache_duration` or `request_timeout` isn't a `timedelta`. | ||
| """ | ||
|
|
@@ -37,14 +41,18 @@ def __init__(self, configuration: OctopusFeatureConfiguration) -> None: | |
| self._configuration = copy.copy(configuration) | ||
| _validate(self._configuration) | ||
| self._evaluator_cache = FeatureFlagEvaluatorCache( | ||
| FeatureFlagApiClient(self._configuration) | ||
| FeatureFlagApiClient(self._configuration), | ||
| self._configuration.cache_duration, | ||
| ) | ||
|
|
||
| def initialize(self, evaluation_context: EvaluationContext) -> None: | ||
| # Never raises, so the SDK reports the provider as ready even when the | ||
| # fetch fails. Every flag is then missing. | ||
| # fetch fails. Every flag is then missing until a refresh succeeds. | ||
| self._evaluator_cache.initialize() | ||
|
|
||
| def shutdown(self) -> None: | ||
| self._evaluator_cache.shutdown() | ||
|
|
||
| def get_metadata(self) -> Metadata: | ||
| return Metadata(name="octopus-python-provider") | ||
|
|
||
|
|
@@ -108,6 +116,12 @@ def _validate(configuration: OctopusFeatureConfiguration) -> None: | |
| if not client_identifier.strip(): | ||
| raise ValueError("client_identifier must not be empty.") | ||
| _validate_positive_duration("cache_duration", configuration.cache_duration) | ||
| # The polling thread waits this long between checks, and a longer wait | ||
| # raises OverflowError there, which would stop polling without a log. | ||
| if configuration.cache_duration > MAX_CACHE_DURATION: | ||
| raise ValueError( | ||
| f"cache_duration must be at most {MAX_CACHE_DURATION}, but was {configuration.cache_duration}." | ||
| ) | ||
| _validate_positive_duration("request_timeout", configuration.request_timeout) | ||
|
|
||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Only do this if consumer does not pass in a
http_client, so that we do not close the http client consumer passed in unexpectedly.