Description
Context
I'm using local evaluation mode. If Flagsmith is unavailable when a new container starts, I want to use the most recent feature state available to me. It's important to avoid fallback to feature states that are too old. Also, I want to avoid additional work for developers to support the default state in code just for the rare case of Flagsmith downtime during a new container start.
I plan to save the environment document while building the container.
I configured Flagsmith as follows:
local_file_handler = LocalFileHandler(environment_document_path="/app/flags.json")
flagsmith = Flagsmith(
environment_key=os.getenv("FLAGSMITH_API_KEY"),
enable_local_evaluation=True,
offline_handler=local_file_handler)
But offline_handler is not used in local evaluation mode, so if during container start Flagsmith is unavailable, I get an implementation error:
feature_backend | File "/app/backend/main.py", line 8, in <module>
feature_backend | flagsmith = Flagsmith(
feature_backend | ^^^^^^^^^^
feature_backend | File "/usr/local/lib/python3.11/site-packages/flagsmith/flagsmith.py", line 163, in __init__
feature_backend | self._initialise_local_evaluation()
feature_backend | File "/usr/local/lib/python3.11/site-packages/flagsmith/flagsmith.py", line 189, in _initialise_local_evaluation
feature_backend | self.update_environment()
feature_backend | File "/usr/local/lib/python3.11/site-packages/flagsmith/flagsmith.py", line 284, in update_environment
feature_backend | self._environment = self._get_environment_from_api()
feature_backend | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
feature_backend | File "/usr/local/lib/python3.11/site-packages/flagsmith/flagsmith.py", line 296, in _get_environment_from_api
feature_backend | environment_data = self._get_json_response(self.environment_url, method="GET")
feature_backend | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
feature_backend | File "/usr/local/lib/python3.11/site-packages/flagsmith/flagsmith.py", line 383, in _get_json_response
feature_backend | raise FlagsmithAPIError(
feature_backend | flagsmith.exceptions.FlagsmithAPIError: Unable to get valid response from Flagsmith API.
Requirements
If Flagsmith is unavailable during container start, use environment from offline_handler until Flagsmith becomes available.
Implementation
_environment
is loaded from offline_handler at the very beginning, so it should be enough to catch api error if _environment is not empty in 2 places:
- https://github.com/Flagsmith/flagsmith-python-client/blob/main/flagsmith/flagsmith.py#L163
- https://github.com/Flagsmith/flagsmith-python-client/blob/main/flagsmith/flagsmith.py#L180
When Flagmisth becomes available, EnvironmentDataPollingManager will automatically update _environment, and we won't fallback to data from offline_handler anymore. So, it seems like no additional changes are needed.
Additiona links
Here is a repository for reproducing the error.