diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea2923d0..89a68924 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,15 +54,7 @@ jobs: - name: start contract test service run: make start-contract-test-service-bg - - name: Run contract tests v2 - uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1 - with: - test_service_port: 9000 - token: ${{ secrets.GITHUB_TOKEN }} - stop_service: "false" - enable_persistence_tests: "true" - - - name: Run contract tests v3 + - name: Run contract tests uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1 with: test_service_port: 9000 @@ -77,15 +69,7 @@ jobs: - name: start async contract test service run: make start-async-contract-test-service-bg - - name: Run async contract tests v2 - uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1 - with: - test_service_port: 9001 - token: ${{ secrets.GITHUB_TOKEN }} - stop_service: "false" - enable_persistence_tests: "true" - - - name: Run async contract tests v3 + - name: Run async contract tests uses: launchdarkly/gh-actions/actions/contract-tests@contract-tests-v1 with: test_service_port: 9001 @@ -166,6 +150,7 @@ jobs: test_service_port: 9000 enable_persistence_tests: "false" token: ${{ secrets.GITHUB_TOKEN }} + version: v3 - name: Start the async contract test service from the sdist working-directory: ${{ runner.temp }}/sdist @@ -177,6 +162,7 @@ jobs: test_service_port: 9001 enable_persistence_tests: "false" token: ${{ secrets.GITHUB_TOKEN }} + version: v3 windows: runs-on: windows-latest diff --git a/Makefile b/Makefile index efb47a4d..5640ddc1 100644 --- a/Makefile +++ b/Makefile @@ -81,8 +81,8 @@ start-async-contract-test-service-bg: .PHONY: run-contract-tests run-contract-tests: - @curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v2/downloader/run.sh \ - | VERSION=v2 PARAMS="-url http://localhost:$(PORT) -debug -stop-service-at-end" sh + @curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v3/downloader/run.sh \ + | VERSION=v3 PARAMS="-url http://localhost:$(PORT) -debug -stop-service-at-end" sh .PHONY: contract-tests contract-tests: #! Run the contract test harness diff --git a/contract-tests/async_client_entity.py b/contract-tests/async_client_entity.py index f835c175..33b4ab63 100644 --- a/contract-tests/async_client_entity.py +++ b/contract-tests/async_client_entity.py @@ -84,25 +84,6 @@ async def start(self): datasystem_config = config_params.get('dataSystem') if datasystem_config is not None: opts["datasystem_config"] = _build_async_data_system(datasystem_config, opts) - elif config_params.get("streaming") is not None: - streaming = config_params["streaming"] - if streaming.get("baseUri") is not None: - opts["stream_uri"] = streaming["baseUri"] - if streaming.get("filter") is not None: - opts["payload_filter_key"] = streaming["filter"] - _set_optional_time_prop(streaming, "initialRetryDelayMs", opts, "initial_reconnect_delay") - elif config_params.get("polling") is not None: - opts['stream'] = False - polling = config_params["polling"] - if polling.get("baseUri") is not None: - opts["base_uri"] = polling["baseUri"] - if polling.get("filter") is not None: - opts["payload_filter_key"] = polling["filter"] - _set_optional_time_prop(polling, "pollIntervalMs", opts, "poll_interval") - elif not endpoints.get('streaming') and not endpoints.get('polling'): - # No data source config and no streaming or polling endpoint means daemon mode. - # A config that sets only an endpoint gets the default streaming data source. - opts['use_ldd'] = True if config_params.get("events") is not None: events = config_params["events"] @@ -135,9 +116,6 @@ async def start(self): _set_optional_time_prop(big_params, "staleAfterMs", big_config, "stale_after") opts["big_segments"] = AsyncBigSegmentsConfig(**big_config) - if config_params.get("persistentDataStore") is not None: - opts["feature_store"] = _create_async_persistent_store(config_params["persistentDataStore"]) - start_wait = config_params.get("startWaitTimeMs") or 5000 sdk_config = AsyncConfig(**opts) diff --git a/contract-tests/async_service.py b/contract-tests/async_service.py index ac87e64b..f13167ee 100644 --- a/contract-tests/async_service.py +++ b/contract-tests/async_service.py @@ -51,7 +51,6 @@ async def handle_status(request: aiohttp.web.Request) -> aiohttp.web.Response: 'all-flags-details-only-for-tracked-flags', 'big-segments', 'context-type', - 'filtering', 'secure-mode-hash', 'tags', 'event-gzip', @@ -69,8 +68,6 @@ async def handle_status(request: aiohttp.web.Request) -> aiohttp.web.Response: 'migrations', 'persistent-data-store-redis', 'fdv1-fallback', - 'retry-conformance-fdv1-streaming', - 'retry-conformance-fdv1-polling', 'service-endpoints', 'wrapper', 'http-proxy', diff --git a/contract-tests/client_entity.py b/contract-tests/client_entity.py index fe617f84..a4a6b806 100644 --- a/contract-tests/client_entity.py +++ b/contract-tests/client_entity.py @@ -131,26 +131,6 @@ def __init__(self, tag, config): opts["datasystem_config"] = datasystem.build() - elif config.get("streaming") is not None: - streaming = config["streaming"] - if streaming.get("baseUri") is not None: - opts["stream_uri"] = streaming["baseUri"] - if streaming.get("filter") is not None: - opts["payload_filter_key"] = streaming["filter"] - _set_optional_time_prop(streaming, "initialRetryDelayMs", opts, "initial_reconnect_delay") - elif config.get("polling") is not None: - opts['stream'] = False - polling = config["polling"] - if polling.get("baseUri") is not None: - opts["base_uri"] = polling["baseUri"] - if polling.get("filter") is not None: - opts["payload_filter_key"] = polling["filter"] - _set_optional_time_prop(polling, "pollIntervalMs", opts, "poll_interval") - elif not endpoints.get('streaming') and not endpoints.get('polling'): - # No data source config and no streaming or polling endpoint means daemon mode. - # A config that sets only an endpoint gets the default streaming data source. - opts['use_ldd'] = True - if config.get("events") is not None: events = config["events"] opts["enable_event_compression"] = events.get("enableGzip", False) @@ -179,9 +159,6 @@ def __init__(self, tag, config): _set_optional_time_prop(big_params, "staleAfterMs", big_config, "stale_after") opts["big_segments"] = BigSegmentsConfig(**big_config) - if config.get("persistentDataStore") is not None: - opts["feature_store"] = _create_persistent_store(config["persistentDataStore"]) - start_wait = config.get("startWaitTimeMs") or 5000 config = Config(**opts) diff --git a/contract-tests/service.py b/contract-tests/service.py index 4631fdee..7abdf951 100644 --- a/contract-tests/service.py +++ b/contract-tests/service.py @@ -65,7 +65,6 @@ def status(): 'all-flags-details-only-for-tracked-flags', 'big-segments', 'context-type', - 'filtering', 'secure-mode-hash', 'tags', 'migrations', @@ -86,8 +85,6 @@ def status(): 'flag-change-listeners', 'flag-value-change-listeners', 'fdv1-fallback', - 'retry-conformance-fdv1-streaming', - 'retry-conformance-fdv1-polling', 'service-endpoints', 'wrapper', 'http-proxy', diff --git a/docs/api-testing.rst b/docs/api-testing.rst index c9faee05..ce496256 100644 --- a/docs/api-testing.rst +++ b/docs/api-testing.rst @@ -1,12 +1,12 @@ Test fixtures ============= -ldclient.integrations.test_data module --------------------------------------- +ldclient.integrations.test_datav2 module +---------------------------------------- -The entry point for this feature is :class:`ldclient.integrations.test_data.TestData`. +The entry point for this feature is :class:`ldclient.integrations.test_datav2.TestDataV2`. -.. automodule:: ldclient.integrations.test_data +.. automodule:: ldclient.integrations.test_datav2 :members: :special-members: __init__ :show-inheritance: diff --git a/ldclient/async_client.py b/ldclient/async_client.py index 3d4b9034..c09893e2 100644 --- a/ldclient/async_client.py +++ b/ldclient/async_client.py @@ -7,8 +7,8 @@ from typing import Any, Callable, List, Optional, Tuple from uuid import uuid4 -from ldclient.async_config import AsyncConfig -from ldclient.async_feature_store import AsyncInMemoryFeatureStore +from ldclient import async_datasystem +from ldclient.async_config import AsyncConfig, AsyncDataSystemConfig from ldclient.context import Context from ldclient.evaluation import EvaluationDetail, FeatureFlagsState from ldclient.hook import ( @@ -52,6 +52,18 @@ from ldclient.versioned_data_kind import FEATURES, SEGMENTS +def _is_daemon_mode(datasystem_config: AsyncDataSystemConfig) -> bool: + """ + Return true if the data system has a persistent store and no data sources. The SDK then reads + flags only from the store, which another process such as the Relay Proxy keeps up to date. + """ + return _has_no_data_sources(datasystem_config) and datasystem_config.data_store is not None + + +def _has_no_data_sources(datasystem_config: AsyncDataSystemConfig) -> bool: + return not datasystem_config.initializers and not datasystem_config.synchronizers + + class AsyncLDClient: """Async LaunchDarkly SDK client. @@ -76,6 +88,7 @@ def __init__(self, config: AsyncConfig): self._config = config self._config._instance_id = str(uuid4()) + self._datasystem_config = config.datasystem_config or async_datasystem.default().build() self._lifecycle_lock = asyncio.Lock() self._started = False @@ -202,17 +215,17 @@ async def __start_up(self, start_wait: float): # Start the big-segment status poll now that a loop is running. self.__big_segment_store_manager.start() - # FDv2 builds its data sources from builders; wire the shared session into - # them before starting (FDv1 pulls the session itself via its provider). - datasystem_config = self._config.datasystem_config - if datasystem_config is not None and not self._config.offline: - self._wire_data_source_sessions(datasystem_config) + # The data system builds its data sources from builders. Give the shared + # session to the builders before the data system starts. + if not self._config.offline: + self._wire_data_source_sessions(self._datasystem_config) if self._config.offline: log.info("Started LaunchDarkly Client in offline mode") - - if self._config.use_ldd: - log.info("Started LaunchDarkly Client in LDD mode") + elif _is_daemon_mode(self._datasystem_config): + log.info("Started LaunchDarkly Client in daemon mode") + elif _has_no_data_sources(self._datasystem_config): + log.warning("The data system has no data sources and no persistent store. All evaluations will return default values.") diagnostic_accumulator = self._set_event_processor(self._config) @@ -224,7 +237,7 @@ async def __start_up(self, start_wait: float): update_processor_ready = AsyncEvent() self._data_system.start(update_processor_ready) - if not self._config.offline and not self._config.use_ldd: + if not self._config.offline and not _is_daemon_mode(self._datasystem_config): if start_wait > 60: log.warning(f"Client was configured to block for up to {start_wait} seconds when initializing. We recommend blocking no longer than 60.") @@ -239,7 +252,7 @@ async def __start_up(self, start_wait: float): def _get_session(self): """Return the shared aiohttp session, creating it on first use inside the - event loop. Nothing creates it in offline/LDD mode, because no network + event loop. Nothing creates it in offline or daemon mode, because no network component asks for it. Uses the same factory as the async transport so SSL/cert setup and proxy handling stay consistent (proxies are resolved per request, so the session itself has trust_env=False).""" @@ -248,23 +261,9 @@ def _get_session(self): return self._session def _make_data_system(self) -> AsyncDataSystem: - datasystem_config = self._config.datasystem_config - if datasystem_config is None: - from ldclient.impl.datasystem.async_fdv1 import AsyncFDv1 - - return AsyncFDv1(self._config, self._select_feature_store(), self._get_session) - from ldclient.impl.datasystem.async_fdv2 import AsyncFDv2 - return AsyncFDv2(self._config, datasystem_config) - - def _select_feature_store(self) -> AsyncFeatureStore: - """Choose the async feature store for the v1 data system based on the - configured store.""" - feature_store = self._config.feature_store - if feature_store is None: - return AsyncInMemoryFeatureStore() - return feature_store + return AsyncFDv2(self._config, self._datasystem_config) def _wire_data_source_sessions(self, data_system_config) -> None: """Provide the client's aiohttp session to any async data source @@ -394,7 +393,7 @@ async def is_initialized(self) -> bool: This is a coroutine because determining readiness may query a persistent store. """ - if self.is_offline() or self._config.use_ldd: + if self.is_offline(): return True return (await self._data_system.data_availability()).at_least(DataAvailability.CACHED) @@ -499,7 +498,7 @@ async def _evaluate_internal(self, key: str, context: Context, default: Any, eve return EvaluationDetail(default, None, error_reason('CLIENT_NOT_READY')), None availability = await self._data_system.data_availability() - if availability != DataAvailability.REFRESHED: + if not availability.at_least(self._data_system.target_availability): if availability == DataAvailability.CACHED: if not self._eval_cached_data_warned: self._eval_cached_data_warned = True @@ -573,7 +572,7 @@ async def all_flags_state(self, context: Context, **kwargs) -> FeatureFlagsState return FeatureFlagsState(False) availability = await self._data_system.data_availability() - if availability != DataAvailability.REFRESHED: + if not availability.at_least(self._data_system.target_availability): if availability == DataAvailability.CACHED: if not self._all_flags_cached_data_warned: self._all_flags_cached_data_warned = True diff --git a/ldclient/async_config.py b/ldclient/async_config.py index 213fe60b..391c1f80 100644 --- a/ldclient/async_config.py +++ b/ldclient/async_config.py @@ -11,22 +11,18 @@ from dataclasses import dataclass from typing import Callable, List, Optional, Set -from ldclient.async_feature_store import AsyncInMemoryFeatureStore from ldclient.config import ( DEFAULT_BASE_URI, DEFAULT_EVENTS_URI, DEFAULT_INITIAL_RECONNECT_DELAY, DEFAULT_POLL_INTERVAL, DEFAULT_STREAM_URI, - GET_LATEST_FEATURES_PATH, - STREAM_FLAGS_PATH, DataSourceBuilder, DataSourceBuilderConfig, HTTPConfig, PrivateAttributesConfig ) from ldclient.hook import Hook -from ldclient.impl.aio.concurrency import AsyncEvent from ldclient.impl.util import ( log, validate_application_info, @@ -34,12 +30,10 @@ ) from ldclient.interfaces import ( AsyncBigSegmentStore, - AsyncDataSourceUpdateSink, AsyncEventProcessor, AsyncFeatureStore, AsyncInitializer, AsyncSynchronizer, - AsyncUpdateProcessor, DataStoreMode ) from ldclient.plugin import AsyncPlugin @@ -145,20 +139,16 @@ class AsyncConfig(DataSourceBuilderConfig, PrivateAttributesConfig): def __init__( self, sdk_key: str, + *, base_uri: str = DEFAULT_BASE_URI, events_uri: str = DEFAULT_EVENTS_URI, events_max_pending: int = 10000, flush_interval: float = 5, stream_uri: str = DEFAULT_STREAM_URI, - stream: bool = True, initial_reconnect_delay: float = DEFAULT_INITIAL_RECONNECT_DELAY, defaults: dict = {}, send_events: Optional[bool] = None, - update_processor_class: Optional[Callable[['AsyncConfig', AsyncFeatureStore, AsyncEvent], AsyncUpdateProcessor]] = None, poll_interval: float = DEFAULT_POLL_INTERVAL, - use_ldd: bool = False, - feature_store: Optional[AsyncFeatureStore] = None, - feature_requester_class=None, event_processor_class: Optional[Callable[['AsyncConfig'], AsyncEventProcessor]] = None, private_attributes: Set[str] = set(), all_attributes_private: bool = False, @@ -176,7 +166,6 @@ def __init__( plugins: Optional[List[AsyncPlugin]] = None, enable_event_compression: bool = True, omit_anonymous_contexts: bool = False, - payload_filter_key: Optional[str] = None, datasystem_config: Optional[AsyncDataSystemConfig] = None, ): """ @@ -192,8 +181,6 @@ def __init__( the flush interval means that the event buffer is less likely to reach capacity. :param stream_uri: The URL for the LaunchDarkly streaming events server. Most users should use the default value. - :param stream: Whether or not the streaming API should be used to receive flag updates. By - default, it is enabled. Streaming should only be disabled on the advice of LaunchDarkly support. :param initial_reconnect_delay: The initial reconnect delay (in seconds) for the streaming connection. The streaming service uses a backoff algorithm (with jitter) every time the connection needs to be reestablished. The delay for the first reconnection will start near this value, and then @@ -205,27 +192,17 @@ def __init__( default values are returned for all flags and no remote network requests are made. By default, this is false. :param poll_interval: The number of seconds between polls for flag updates if streaming is off. - :param use_ldd: Whether you are using the LaunchDarkly Relay Proxy in daemon mode. In this - configuration, the client will not use a streaming connection to listen for updates, but instead - will get feature state from a Redis instance. The ``stream`` and ``poll_interval`` options will be - ignored if this option is set to true. By default, this is false. - For more information, read the LaunchDarkly - documentation: https://docs.launchdarkly.com/home/relay-proxy/using#using-daemon-mode :param array private_attributes: Marks a set of attributes private. Any users sent to LaunchDarkly with this configuration active will have these attributes removed. Each item can be either the name of an attribute ("email"), or a slash-delimited path ("/address/street") to mark a property within a JSON object value as private. :param all_attributes_private: If true, all user attributes (other than the key) will be private, not just the attributes specified in ``private_attributes``. - :param feature_store: An AsyncFeatureStore implementation :param context_keys_capacity: The number of context keys that the event processor can remember at any one time, so that duplicate context details will not be sent in analytics events. :param context_keys_flush_interval: The interval in seconds at which the event processor will reset its set of known context keys. - :param feature_requester_class: A factory for a FeatureRequester implementation taking the sdk key and config :param event_processor_class: A factory for an AsyncEventProcessor implementation taking the config - :param update_processor_class: A factory for an UpdateProcessor implementation taking the config, an - AsyncFeatureStore implementation, and an AsyncEvent to signal readiness. :param diagnostic_opt_out: Unless this field is set to True, the client will send some diagnostics data to the LaunchDarkly servers in order to assist in the development of future SDK improvements. These diagnostics consist of an initial payload containing some details of SDK in use, @@ -251,22 +228,18 @@ def __init__( set this to False to prevent extra CPU use, because the Relay Proxy decompresses and recompresses the payloads. :param omit_anonymous_contexts: Sets whether anonymous contexts should be omitted from index and identify events. - :param payload_filter_key: The payload filter is used to selectively limited the flags and segments delivered in the data source payload. Payload filtering is not supported with the FDv2 data system, so this has no effect on FDv2 requests. - :param datasystem_config: Configuration for the data system, which controls how the SDK gets flag and segment data. When set, it overrides ``feature_store``, ``update_processor_class``, ``stream``, and ``use_ldd``. + :param datasystem_config: Configuration for the data system, which controls how the SDK gets flag and + segment data. Build it with the functions in :mod:`ldclient.async_datasystem`. If it is not set, the + SDK uses :func:`ldclient.async_datasystem.default`. """ self.__sdk_key = validate_sdk_key_format(sdk_key, log) self.__base_uri = base_uri.rstrip('/') self.__events_uri = events_uri.rstrip('/') self.__stream_uri = stream_uri.rstrip('/') - self.__update_processor_class = update_processor_class - self.__stream = stream self.__initial_reconnect_delay = initial_reconnect_delay self.__poll_interval = max(poll_interval, DEFAULT_POLL_INTERVAL) - self.__use_ldd = use_ldd - self.__feature_store = AsyncInMemoryFeatureStore() if not feature_store else feature_store self.__event_processor_class = event_processor_class - self.__feature_requester_class = feature_requester_class self.__events_max_pending = events_max_pending self.__flush_interval = flush_interval self.__defaults = defaults @@ -289,8 +262,6 @@ def __init__( self.__plugins = [plugin for plugin in plugins if isinstance(plugin, AsyncPlugin)] if plugins else [] self.__enable_event_compression = enable_event_compression self.__omit_anonymous_contexts = omit_anonymous_contexts - self.__payload_filter_key = payload_filter_key - self._data_source_update_sink: Optional[AsyncDataSourceUpdateSink] = None self.__instance_id: Optional[str] = None self._datasystem_config = datasystem_config @@ -306,11 +277,6 @@ def sdk_key(self) -> Optional[str]: def base_uri(self) -> str: return self.__base_uri - # for internal use only - also no longer used, will remove - @property - def get_latest_flags_uri(self): - return self.__base_uri + GET_LATEST_FEATURES_PATH - # for internal use only @property def events_base_uri(self): @@ -326,19 +292,6 @@ def events_uri(self): def stream_base_uri(self) -> str: return self.__stream_uri - # for internal use only - should construct the URL path in the streaming code, not here - @property - def stream_uri(self): - return self.__stream_uri + STREAM_FLAGS_PATH - - @property - def update_processor_class(self) -> Optional[Callable[['AsyncConfig', AsyncFeatureStore, AsyncEvent], AsyncUpdateProcessor]]: - return self.__update_processor_class - - @property - def stream(self) -> bool: - return self.__stream - @property def initial_reconnect_delay(self) -> float: return self.__initial_reconnect_delay @@ -347,22 +300,10 @@ def initial_reconnect_delay(self) -> float: def poll_interval(self) -> float: return self.__poll_interval - @property - def use_ldd(self) -> bool: - return self.__use_ldd - - @property - def feature_store(self) -> AsyncFeatureStore: - return self.__feature_store - @property def event_processor_class(self) -> Optional[Callable[['AsyncConfig'], AsyncEventProcessor]]: return self.__event_processor_class - @property - def feature_requester_class(self) -> Optional[Callable]: - return self.__feature_requester_class - @property def send_events(self) -> bool: return self.__send_events @@ -465,29 +406,6 @@ def omit_anonymous_contexts(self) -> bool: """ return self.__omit_anonymous_contexts - @property - def payload_filter_key(self) -> Optional[str]: - """ - LaunchDarkly Server SDKs historically downloaded all flag configuration - and segments for a particular environment during initialization. - - For some customers, this is an unacceptably large amount of data, and - has contributed to performance issues within their products. - - Filtered environments aim to solve this problem. By allowing customers - to specify subsets of an environment's flags using a filter key, SDKs - will initialize faster and use less memory. - - This payload filter key only applies to the default streaming and - polling data sources. It will not affect TestData or FileData data - sources, nor will it be applied to any data source provided through the - {#data_source} config property. - - Payload filtering is not supported with the FDv2 data system, so this - key has no effect on requests made by FDv2 data sources. - """ - return self.__payload_filter_key - @property def _instance_id(self) -> Optional[str]: """The instance ID included in request headers. Set by the SDK.""" @@ -497,20 +415,6 @@ def _instance_id(self) -> Optional[str]: def _instance_id(self, value: Optional[str]) -> None: self.__instance_id = value - @property - def data_source_update_sink(self) -> Optional[AsyncDataSourceUpdateSink]: - """ - Returns the component that allows a data source to push data into the SDK. - - This property should only be set by the SDK. Long term access of this - property is not supported; it is temporarily being exposed to maintain - backwards compatibility while the SDK structure is updated. - - Custom data source implementations should integrate with this sink if - they want to provide support for data source status listeners. - """ - return self._data_source_update_sink - @property def datasystem_config(self) -> Optional[AsyncDataSystemConfig]: """ diff --git a/ldclient/client.py b/ldclient/client.py index c5a56a9b..0ca567c3 100644 --- a/ldclient/client.py +++ b/ldclient/client.py @@ -8,7 +8,8 @@ from typing import Any, Callable, Dict, List, Optional, Tuple from uuid import uuid4 -from ldclient.config import Config +from ldclient import datasystem +from ldclient.config import Config, DataSystemConfig from ldclient.context import Context from ldclient.evaluation import EvaluationDetail, FeatureFlagsState from ldclient.hook import ( @@ -54,6 +55,18 @@ ) +def _is_daemon_mode(datasystem_config: DataSystemConfig) -> bool: + """ + Return true if the data system has a persistent store and no data sources. The SDK then reads + flags only from the store, which another process such as the Relay Proxy keeps up to date. + """ + return _has_no_data_sources(datasystem_config) and datasystem_config.data_store is not None + + +def _has_no_data_sources(datasystem_config: DataSystemConfig) -> bool: + return not datasystem_config.initializers and not datasystem_config.synchronizers + + class LDClient: """The LaunchDarkly SDK client object. @@ -76,6 +89,7 @@ def __init__(self, config: Config, start_wait: float = 5): self._config = config self._config._instance_id = str(uuid4()) self._config._validate() + self._datasystem_config = config.datasystem_config or datasystem.default().build() self._event_processor = None self._event_factory_default = EventFactory(False) @@ -146,13 +160,13 @@ def _check_forked(self): def _fork_breaks_client(self) -> bool: """ - Return true if this configuration needs background threads. Offline mode has none. LDD mode - with events disabled reads flags from the persistent store and sends nothing, so a fork does - not break it. + Return true if this configuration needs background threads. Offline mode has none. Daemon + mode with events disabled reads flags from the persistent store and sends nothing, so a fork + does not break it. """ if self._config.offline: return False - if self._config.use_ldd and not self._config.send_events: + if _is_daemon_mode(self._datasystem_config) and not self._config.send_events: return False return True @@ -163,16 +177,7 @@ def __start_up(self, start_wait: float): self.__hooks_lock = ReadWriteLock() self.__hooks = self._config.hooks + plugin_hooks # type: List[Hook] - datasystem_config = self._config.datasystem_config - if datasystem_config is None: - # Initialize data system (FDv1) to encapsulate v1 data plumbing - from ldclient.impl.datasystem.fdv1 import ( # local import to avoid circular dependency - FDv1 - ) - - self._data_system: DataSystem = FDv1(self._config) - else: - self._data_system = FDv2(self._config, datasystem_config) + self._data_system: DataSystem = FDv2(self._config, self._datasystem_config) self.__flag_tracker = FlagTrackerImpl( self._data_system.flag_change_listeners, @@ -196,9 +201,10 @@ def __start_up(self, start_wait: float): if self._config.offline: log.info("Started LaunchDarkly Client in offline mode") - - if self._config.use_ldd: - log.info("Started LaunchDarkly Client in LDD mode") + elif _is_daemon_mode(self._datasystem_config): + log.info("Started LaunchDarkly Client in daemon mode") + elif _has_no_data_sources(self._datasystem_config): + log.warning("The data system has no data sources and no persistent store. All evaluations will return default values.") diagnostic_accumulator = self._set_event_processor(self._config) @@ -210,7 +216,7 @@ def __start_up(self, start_wait: float): update_processor_ready = threading.Event() self._data_system.start(update_processor_ready) - if not self._config.offline and not self._config.use_ldd: + if not self._config.offline and not _is_daemon_mode(self._datasystem_config): if start_wait > 60: log.warning(f"Client was configured to block for up to {start_wait} seconds when initializing. We recommend blocking no longer than 60.") @@ -338,7 +344,7 @@ def is_initialized(self) -> bool: If this returns true, it means the client has data it can use to evaluate flags. That could be because it connected to LaunchDarkly at least once and received flag data, or because it has - cached data from a persistent store, or because it was configured for offline or LDD (daemon) + cached data from a persistent store, or because it was configured for offline or daemon mode. It could still have encountered a connection problem after that point, and cached data may not be current, so this does not guarantee that the flag data is up to date; if you need to know the connection status in more detail, use :attr:`data_source_status_provider`. @@ -353,7 +359,7 @@ def is_initialized(self) -> bool: :return: true if the client is initialized and has flag data available """ - if self.is_offline() or self._config.use_ldd: + if self.is_offline(): return True return self._data_system.data_availability.at_least(DataAvailability.CACHED) @@ -445,7 +451,7 @@ def _evaluate_internal(self, key: str, context: Context, default: Any, event_fac return EvaluationDetail(default, None, error_reason('CLIENT_NOT_READY')), None availability = self._data_system.data_availability - if availability != DataAvailability.REFRESHED: + if not availability.at_least(self._data_system.target_availability): if availability == DataAvailability.CACHED: if not self._eval_cached_data_warned: with self._cached_data_warning_lock: @@ -523,7 +529,7 @@ def all_flags_state(self, context: Context, **kwargs) -> FeatureFlagsState: self._check_forked() availability = self._data_system.data_availability - if availability != DataAvailability.REFRESHED: + if not availability.at_least(self._data_system.target_availability): if availability == DataAvailability.CACHED: if not self._all_flags_cached_data_warned: with self._cached_data_warning_lock: diff --git a/ldclient/config.py b/ldclient/config.py index b6a476a0..d19aa7e7 100644 --- a/ldclient/config.py +++ b/ldclient/config.py @@ -5,12 +5,9 @@ """ import copy -import warnings from dataclasses import dataclass -from threading import Event from typing import Callable, List, Optional, Protocol, Set, TypeVar -from ldclient.feature_store import InMemoryFeatureStore from ldclient.hook import Hook from ldclient.impl.util import ( log, @@ -19,19 +16,14 @@ ) from ldclient.interfaces import ( BigSegmentStore, - DataSourceUpdateSink, DataStoreMode, EventProcessor, FeatureStore, Initializer, - Synchronizer, - UpdateProcessor + Synchronizer ) from ldclient.plugin import Plugin -GET_LATEST_FEATURES_PATH = '/sdk/latest-flags' -STREAM_FLAGS_PATH = '/flags' - DEFAULT_BASE_URI = 'https://app.launchdarkly.com' DEFAULT_EVENTS_URI = 'https://events.launchdarkly.com' DEFAULT_STREAM_URI = 'https://stream.launchdarkly.com' @@ -290,20 +282,16 @@ class Config(DataSourceBuilderConfig, PrivateAttributesConfig): def __init__( self, sdk_key: str, + *, base_uri: str = DEFAULT_BASE_URI, events_uri: str = DEFAULT_EVENTS_URI, events_max_pending: int = 10000, flush_interval: float = 5, stream_uri: str = DEFAULT_STREAM_URI, - stream: bool = True, initial_reconnect_delay: float = DEFAULT_INITIAL_RECONNECT_DELAY, defaults: dict = {}, send_events: Optional[bool] = None, - update_processor_class: Optional[Callable[['Config', FeatureStore, Event], UpdateProcessor]] = None, poll_interval: float = DEFAULT_POLL_INTERVAL, - use_ldd: bool = False, - feature_store: Optional[FeatureStore] = None, - feature_requester_class=None, event_processor_class: Optional[Callable[['Config'], EventProcessor]] = None, private_attributes: Set[str] = set(), all_attributes_private: bool = False, @@ -321,7 +309,6 @@ def __init__( plugins: Optional[List[Plugin]] = None, enable_event_compression: bool = True, omit_anonymous_contexts: bool = False, - payload_filter_key: Optional[str] = None, datasystem_config: Optional[DataSystemConfig] = None, ): """ @@ -337,8 +324,6 @@ def __init__( the flush interval means that the event buffer is less likely to reach capacity. :param stream_uri: The URL for the LaunchDarkly streaming events server. Most users should use the default value. - :param stream: Whether or not the streaming API should be used to receive flag updates. By - default, it is enabled. Streaming should only be disabled on the advice of LaunchDarkly support. :param initial_reconnect_delay: The initial reconnect delay (in seconds) for the streaming connection. The streaming service uses a backoff algorithm (with jitter) every time the connection needs to be reestablished. The delay for the first reconnection will start near this value, and then @@ -350,27 +335,17 @@ def __init__( default values are returned for all flags and no remote network requests are made. By default, this is false. :param poll_interval: The number of seconds between polls for flag updates if streaming is off. - :param use_ldd: Whether you are using the LaunchDarkly Relay Proxy in daemon mode. In this - configuration, the client will not use a streaming connection to listen for updates, but instead - will get feature state from a Redis instance. The ``stream`` and ``poll_interval`` options will be - ignored if this option is set to true. By default, this is false. - For more information, read the LaunchDarkly - documentation: https://docs.launchdarkly.com/home/relay-proxy/using#using-daemon-mode :param array private_attributes: Marks a set of attributes private. Any users sent to LaunchDarkly with this configuration active will have these attributes removed. Each item can be either the name of an attribute ("email"), or a slash-delimited path ("/address/street") to mark a property within a JSON object value as private. :param all_attributes_private: If true, all user attributes (other than the key) will be private, not just the attributes specified in ``private_attributes``. - :param feature_store: A FeatureStore implementation :param context_keys_capacity: The number of context keys that the event processor can remember at any one time, so that duplicate context details will not be sent in analytics events. :param context_keys_flush_interval: The interval in seconds at which the event processor will reset its set of known context keys. - :param feature_requester_class: A factory for a FeatureRequester implementation taking the sdk key and config :param event_processor_class: A factory for an EventProcessor implementation taking the config - :param update_processor_class: A factory for an UpdateProcessor implementation taking the config, a FeatureStore - implementation, and a threading `Event` to signal readiness. :param diagnostic_opt_out: Unless this field is set to True, the client will send some diagnostics data to the LaunchDarkly servers in order to assist in the development of future SDK improvements. These diagnostics consist of an initial payload containing some details of SDK in use, @@ -396,22 +371,18 @@ def __init__( set this to False to prevent extra CPU use, because the Relay Proxy decompresses and recompresses the payloads. :param omit_anonymous_contexts: Sets whether anonymous contexts should be omitted from index and identify events. - :param payload_filter_key: The payload filter is used to selectively limited the flags and segments delivered in the data source payload. Payload filtering is not supported with the FDv2 data system, so this has no effect on FDv2 requests. - :param datasystem_config: Configuration for the data system, which controls how the SDK gets flag and segment data. When set, it overrides ``feature_store``, ``update_processor_class``, ``stream``, and ``use_ldd``. + :param datasystem_config: Configuration for the data system, which controls how the SDK gets flag and + segment data. Build it with the functions in :mod:`ldclient.datasystem`. If it is not set, the SDK + uses :func:`ldclient.datasystem.default`. """ self.__sdk_key = validate_sdk_key_format(sdk_key, log) self.__base_uri = base_uri.rstrip('/') self.__events_uri = events_uri.rstrip('/') self.__stream_uri = stream_uri.rstrip('/') - self.__update_processor_class = update_processor_class - self.__stream = stream self.__initial_reconnect_delay = initial_reconnect_delay self.__poll_interval = max(poll_interval, DEFAULT_POLL_INTERVAL) - self.__use_ldd = use_ldd - self.__feature_store = InMemoryFeatureStore() if not feature_store else feature_store self.__event_processor_class = event_processor_class - self.__feature_requester_class = feature_requester_class self.__events_max_pending = events_max_pending self.__flush_interval = flush_interval self.__defaults = defaults @@ -434,50 +405,9 @@ def __init__( self.__plugins = [plugin for plugin in plugins if isinstance(plugin, Plugin)] if plugins else [] self.__enable_event_compression = enable_event_compression self.__omit_anonymous_contexts = omit_anonymous_contexts - self.__payload_filter_key = payload_filter_key - self._data_source_update_sink: Optional[DataSourceUpdateSink] = None self._instance_id: Optional[str] = None self._datasystem_config = datasystem_config - def copy_with_new_sdk_key(self, new_sdk_key: str) -> 'Config': - """Returns a new ``Config`` instance that is the same as this one, except for having a different SDK key. - The key will not be updated if the provided key contains invalid characters. - - DEPRECATED: This method is deprecated and will be removed in a future version. - - :param new_sdk_key: the new SDK key - """ - warnings.warn("copy_with_new_sdk_key is deprecated and will be removed in a future version", DeprecationWarning, stacklevel=2) - return Config( - sdk_key=new_sdk_key, - base_uri=self.__base_uri, - events_uri=self.__events_uri, - events_max_pending=self.__events_max_pending, - flush_interval=self.__flush_interval, - stream_uri=self.__stream_uri, - stream=self.__stream, - initial_reconnect_delay=self.__initial_reconnect_delay, - defaults=self.__defaults, - send_events=self.__send_events, - update_processor_class=self.__update_processor_class, - poll_interval=self.__poll_interval, - use_ldd=self.__use_ldd, - feature_store=self.__feature_store, - feature_requester_class=self.__feature_requester_class, - event_processor_class=self.__event_processor_class, - private_attributes=self.__private_attributes, - all_attributes_private=self.__all_attributes_private, - offline=self.__offline, - context_keys_capacity=self.__context_keys_capacity, - context_keys_flush_interval=self.__context_keys_flush_interval, - diagnostic_opt_out=self.__diagnostic_opt_out, - diagnostic_recording_interval=self.__diagnostic_recording_interval, - wrapper_name=self.__wrapper_name, - wrapper_version=self.__wrapper_version, - http=self.__http, - big_segments=self.__big_segments, - ) - def with_wrapper_information(self, wrapper_name: Optional[str], wrapper_version: Optional[str] = None) -> 'Config': """Returns a new ``Config`` instance that is the same as this one, except for having different wrapper information. @@ -485,7 +415,7 @@ def with_wrapper_information(self, wrapper_name: Optional[str], wrapper_version: identify themselves rather than the application that configured the client. The new instance is a shallow copy: it shares the objects the original configuration references, such as the - feature store, the logger, and the HTTP configuration. Mutating one of those objects affects both + data system configuration, the hooks, and the HTTP configuration. Mutating one of those objects affects both configurations. :param wrapper_name: an identifying name for the wrapper being used; see :py:attr:`~wrapper_name` @@ -509,11 +439,6 @@ def sdk_key(self) -> Optional[str]: def base_uri(self) -> str: return self.__base_uri - # for internal use only - also no longer used, will remove - @property - def get_latest_flags_uri(self): - return self.__base_uri + GET_LATEST_FEATURES_PATH - # for internal use only @property def events_base_uri(self): @@ -529,19 +454,6 @@ def events_uri(self): def stream_base_uri(self): return self.__stream_uri - # for internal use only - should construct the URL path in the streaming code, not here - @property - def stream_uri(self): - return self.__stream_uri + STREAM_FLAGS_PATH - - @property - def update_processor_class(self) -> Optional[Callable[['Config', FeatureStore, Event], UpdateProcessor]]: - return self.__update_processor_class - - @property - def stream(self) -> bool: - return self.__stream - @property def initial_reconnect_delay(self) -> float: return self.__initial_reconnect_delay @@ -550,22 +462,10 @@ def initial_reconnect_delay(self) -> float: def poll_interval(self) -> float: return self.__poll_interval - @property - def use_ldd(self) -> bool: - return self.__use_ldd - - @property - def feature_store(self) -> FeatureStore: - return self.__feature_store - @property def event_processor_class(self) -> Optional[Callable[['Config'], EventProcessor]]: return self.__event_processor_class - @property - def feature_requester_class(self) -> Optional[Callable]: - return self.__feature_requester_class - @property def send_events(self) -> bool: return self.__send_events @@ -669,43 +569,6 @@ def omit_anonymous_contexts(self) -> bool: """ return self.__omit_anonymous_contexts - @property - def payload_filter_key(self) -> Optional[str]: - """ - LaunchDarkly Server SDKs historically downloaded all flag configuration - and segments for a particular environment during initialization. - - For some customers, this is an unacceptably large amount of data, and - has contributed to performance issues within their products. - - Filtered environments aim to solve this problem. By allowing customers - to specify subsets of an environment's flags using a filter key, SDKs - will initialize faster and use less memory. - - This payload filter key only applies to the default streaming and - polling data sources. It will not affect TestData or FileData data - sources, nor will it be applied to any data source provided through the - {#data_source} config property. - - Payload filtering is not supported with the FDv2 data system, so this - key has no effect on requests made by FDv2 data sources. - """ - return self.__payload_filter_key - - @property - def data_source_update_sink(self) -> Optional[DataSourceUpdateSink]: - """ - Returns the component that allows a data source to push data into the SDK. - - This property should only be set by the SDK. Long term access of this - property is not supported; it is temporarily being exposed to maintain - backwards compatibility while the SDK structure is updated. - - Custom data source implementations should integrate with this sink if - they want to provide support for data source status listeners. - """ - return self._data_source_update_sink - @property def datasystem_config(self) -> Optional[DataSystemConfig]: """ diff --git a/ldclient/feature_store.py b/ldclient/feature_store.py index 2cd50286..ceb54bef 100644 --- a/ldclient/feature_store.py +++ b/ldclient/feature_store.py @@ -18,13 +18,10 @@ class CacheConfig: """Encapsulates caching parameters for feature store implementations that support local caching. - Note: when the SDK is configured to use FDv2 (by setting ``datasystem_config`` - on :class:`ldclient.config.Config`), the persistent-store cache is - automatically replaced with a no-op once the in-memory store has been - initialized. The TTL and capacity configured here therefore only affect - the brief bootstrap window before the first set of flag data has been - received. Under FDv1 (the default data system) the cache continues to - behave as it always has. + Note: the persistent-store cache is automatically replaced with a no-op + once the in-memory store has been initialized. The TTL and capacity + configured here therefore only affect the brief bootstrap window before + the first set of flag data has been received. """ DEFAULT_EXPIRATION = 15.0 diff --git a/ldclient/impl/datasource/__init__.py b/ldclient/impl/datasource/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/ldclient/impl/datasource/async_feature_requester.py b/ldclient/impl/datasource/async_feature_requester.py deleted file mode 100644 index 66a732d5..00000000 --- a/ldclient/impl/datasource/async_feature_requester.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Default implementation of feature flag polling requests. -""" - -import json -from collections import namedtuple -from typing import Optional -from urllib import parse - -from ldclient.impl.aio.transport import AsyncHTTPTransport -from ldclient.impl.datasource.datasource_common import FDV1_POLLING_ENDPOINT -from ldclient.impl.http import ASYNC_USER_AGENT -from ldclient.impl.util import _headers, log, throw_if_unsuccessful_response -from ldclient.interfaces import AsyncFeatureRequester -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -CacheEntry = namedtuple('CacheEntry', ['data', 'etag']) - - -class AsyncFeatureRequesterImpl(AsyncFeatureRequester): - def __init__(self, config, transport: Optional[AsyncHTTPTransport] = None): - self._cache: dict = dict() - # Only close the transport on shutdown if we created it; an injected - # transport is owned by the caller. - self._owns_transport = transport is None - self._transport = transport if transport is not None else AsyncHTTPTransport(config) - self._config = config - self._poll_uri = config.base_uri + FDV1_POLLING_ENDPOINT - if config.payload_filter_key is not None: - self._poll_uri += '?%s' % parse.urlencode({'filter': config.payload_filter_key}) - - async def get_all_data(self): - uri = self._poll_uri - hdrs = _headers(self._config, ASYNC_USER_AGENT) - cache_entry = self._cache.get(uri) - hdrs['Accept-Encoding'] = 'gzip' - if cache_entry is not None: - hdrs['If-None-Match'] = cache_entry.etag - r = await self._transport.request('GET', uri, headers=hdrs) - throw_if_unsuccessful_response(r) - if r.status == 304 and cache_entry is not None: - data = cache_entry.data - etag = cache_entry.etag - from_cache = True - else: - data = json.loads(r.body) - etag = r.headers.get('ETag') - from_cache = False - if etag is not None: - self._cache[uri] = CacheEntry(data=data, etag=etag) - log.debug("%s response status:[%d] From cache? [%s] ETag:[%s]", uri, r.status, from_cache, etag) - - return {FEATURES: data['flags'], SEGMENTS: data['segments']} - - async def close(self): - if self._owns_transport: - await self._transport.close() diff --git a/ldclient/impl/datasource/async_polling.py b/ldclient/impl/datasource/async_polling.py deleted file mode 100644 index 7a07021c..00000000 --- a/ldclient/impl/datasource/async_polling.py +++ /dev/null @@ -1,106 +0,0 @@ -""" -Default implementation of the polling component. -""" - -# currently excluded from documentation - see docs/README.md - -import time -from typing import Optional - -from ldclient.async_config import AsyncConfig -from ldclient.impl.aio.concurrency import AsyncEvent, AsyncRepeatingTask -from ldclient.impl.datasource.datasource_common import require_update_sink -from ldclient.impl.retry import ( - FailureKind, - RetryState, - classify_http_status, - for_polling -) -from ldclient.impl.util import ( - UnsuccessfulResponseException, - http_error_description, - log -) -from ldclient.interfaces import ( - AsyncDataSourceUpdateSink, - AsyncFeatureRequester, - AsyncFeatureStore, - AsyncUpdateProcessor, - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState -) - - -class AsyncPollingUpdateProcessor(AsyncUpdateProcessor): - """Polls LaunchDarkly for flag data on its own background task. - - The loop reads its wait from the retry state, which ``_fetch_and_store`` - updates, so a failure can push the next poll further out than the poll - interval. See :mod:`ldclient.impl.retry`. - """ - - def __init__(self, config: AsyncConfig, requester: AsyncFeatureRequester, store: AsyncFeatureStore, ready: AsyncEvent, retry_state: Optional[RetryState] = None): - self._config = config - self._data_source_update_sink: AsyncDataSourceUpdateSink = require_update_sink(config.data_source_update_sink) - self._requester = requester - self._store = store - self._ready = ready - self._retry = retry_state or for_polling(config.poll_interval) - # No initial delay: the first poll is immediate. - self._task = AsyncRepeatingTask("ldclient.datasource.polling", self._retry, 0, self._fetch_and_store) - - def start(self): - log.info("Starting AsyncPollingUpdateProcessor with request interval: " + str(self._config.poll_interval)) - self._task.start() - - def initialized(self): - return self._ready.is_set() and self._store.initialized - - async def stop(self): - log.info("Stopping AsyncPollingUpdateProcessor") - self._task.stop() - - self._data_source_update_sink.update_status(DataSourceState.OFF, None) - - # Do not close the transport while an in-flight request still uses it. - try: - await self._task.wait_stopped() - finally: - await self._requester.close() - - async def _fetch_and_store(self) -> None: - """Makes one poll request and records the outcome on the retry state.""" - try: - all_data = await self._requester.get_all_data() - await self._data_source_update_sink.init(all_data) - self._data_source_update_sink.update_status(DataSourceState.VALID, None) - - # Report the status before signaling readiness, so a caller that - # wakes on readiness cannot still read INITIALIZING. - if not self._ready.is_set() and self._store.initialized: - log.info("AsyncPollingUpdateProcessor initialized ok") - self._ready.set() - - self._retry.record_success() - return - except UnsuccessfulResponseException as e: - kind = classify_http_status(e.status) - error_info = DataSourceErrorInfo(DataSourceErrorKind.ERROR_RESPONSE, e.status, time.time(), str(e)) - description = "Received %s for polling request" % http_error_description(e.status) - level = log.error if kind is FailureKind.UNEXPECTED else log.warning - stacktrace = None - except Exception as e: - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.UNKNOWN, 0, time.time(), str(e)) - description = "Error encountered when updating flags: %s" % e - level = log.error - # The exception is passed explicitly: by the time the message is - # logged, the handler has exited and exc_info() is empty. - stacktrace = e - - self._retry.record_failure(kind) - delay = self._retry.next_delay - level("%s - will retry in %.1fs" % (description, delay), exc_info=stacktrace) - - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, error_info) diff --git a/ldclient/impl/datasource/async_status.py b/ldclient/impl/datasource/async_status.py deleted file mode 100644 index 29bccdb0..00000000 --- a/ldclient/impl/datasource/async_status.py +++ /dev/null @@ -1,146 +0,0 @@ -import time -from typing import Awaitable, Callable, Dict, Mapping, Optional, Set - -from ldclient.impl.dependency_tracker import DependencyTracker, KindAndKey -from ldclient.impl.listeners import Listeners -from ldclient.interfaces import ( - AsyncDataSourceUpdateSink, - AsyncFeatureStore, - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceStatus, - FlagChange -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS, VersionedDataKind - - -class AsyncDataSourceUpdateSinkImpl(AsyncDataSourceUpdateSink): - def __init__(self, store: AsyncFeatureStore, status_listeners: Listeners, flag_change_listeners: Listeners): - self.__store = store - self.__status_listeners = status_listeners - self.__flag_change_listeners = flag_change_listeners - self.__tracker = DependencyTracker() - - self.__status = DataSourceStatus(DataSourceState.INITIALIZING, time.time(), None) - - @property - def status(self) -> DataSourceStatus: - return self.__status - - async def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]) -> None: - old_data: Optional[Dict[VersionedDataKind, Mapping[str, dict]]] = None - - async def init_store(): - nonlocal old_data - if self.__flag_change_listeners.has_listeners(): - old_data = {} - for kind in [FEATURES, SEGMENTS]: - old_data[kind] = await self.__store.all(kind) - await self.__store.init(all_data) - - await self.__monitor_store_update(init_store) - - self.__reset_tracker_with_new_data(all_data) - - if old_data is None: - return - - self.__send_change_events(self.__compute_changed_items_for_full_data_set(old_data, all_data)) - - async def upsert(self, kind: VersionedDataKind, item: dict) -> None: - key = item.get('key', '') - - updated = await self.__monitor_store_update(lambda: self.__store.upsert(kind, item)) - - # Only update dependency tracking and notify listeners if the store actually applied the - # update. The AsyncFeatureStore contract returns whether it wrote, so a stale - # (version-rejected) upsert produces no spurious flag-change events. - if updated: - self.__update_dependency_for_single_item(kind, key, item) - - async def delete(self, kind: VersionedDataKind, key: str, version: int) -> None: - deleted = await self.__monitor_store_update(lambda: self.__store.delete(kind, key, version)) - - # Only notify when the store actually applied the delete, so a stale (version-rejected) - # delete produces no spurious flag-change events, mirroring the upsert path. - if deleted: - self.__update_dependency_for_single_item(kind, key, None) - - def update_status(self, new_state: DataSourceState, new_error: Optional[DataSourceErrorInfo]) -> None: - status_to_broadcast = None - - old_status = self.__status - - # OFF is terminal. A poll or stream connection that was still in - # flight when the data source stopped must not report after it. - if old_status.state == DataSourceState.OFF: - return - - if new_state == DataSourceState.INTERRUPTED and old_status.state == DataSourceState.INITIALIZING: - new_state = DataSourceState.INITIALIZING - - if new_state == old_status.state and new_error is None: - return - - self.__status = DataSourceStatus( - new_state, - self.__status.since if new_state == self.__status.state else time.time(), - self.__status.error if new_error is None else new_error, - ) - - status_to_broadcast = self.__status - - if status_to_broadcast is not None: - self.__status_listeners.notify(status_to_broadcast) - - async def __monitor_store_update(self, fn: Callable[[], Awaitable]): - try: - return await fn() - except Exception as e: - error_info = DataSourceErrorInfo(DataSourceErrorKind.STORE_ERROR, 0, time.time(), str(e)) - self.update_status(DataSourceState.INTERRUPTED, error_info) - raise - - def __update_dependency_for_single_item(self, kind: VersionedDataKind, key: str, item): - self.__tracker.update_dependencies_from(kind, key, item) - if self.__flag_change_listeners.has_listeners(): - affected_items: Set[KindAndKey] = set() - self.__tracker.add_affected_items(affected_items, KindAndKey(kind=kind, key=key)) - self.__send_change_events(affected_items) - - def __reset_tracker_with_new_data(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]): - self.__tracker.reset() - for kind, items in all_data.items(): - for key, item in items.items(): - self.__tracker.update_dependencies_from(kind, key, item) - - def __send_change_events(self, affected_items: Set[KindAndKey]): - for item in affected_items: - if item.kind == FEATURES: - self.__flag_change_listeners.notify(FlagChange(item.key)) - - def __compute_changed_items_for_full_data_set( - self, - old_data: Mapping[VersionedDataKind, Mapping[str, dict]], - new_data: Mapping[VersionedDataKind, Mapping[str, dict]], - ) -> Set[KindAndKey]: - affected_items: Set[KindAndKey] = set() - - for kind in [FEATURES, SEGMENTS]: - old_items = old_data.get(kind, {}) - new_items = new_data.get(kind, {}) - - keys: Set[str] = set() - - for key in keys.union(old_items.keys(), new_items.keys()): - old_item = old_items.get(key) - new_item = new_items.get(key) - - if old_item is None and new_item is None: - continue - - if old_item is None or new_item is None or old_item['version'] < new_item['version']: - self.__tracker.add_affected_items(affected_items, KindAndKey(kind=kind, key=key)) - - return affected_items diff --git a/ldclient/impl/datasource/async_streaming.py b/ldclient/impl/datasource/async_streaming.py deleted file mode 100644 index 6cda82a9..00000000 --- a/ldclient/impl/datasource/async_streaming.py +++ /dev/null @@ -1,287 +0,0 @@ -""" -Default implementation of the streaming component. -""" - -# currently excluded from documentation - see docs/README.md - -import asyncio -import json -import time -from typing import Any, Callable, Mapping, Optional -from urllib import parse - -from ld_eventsource.actions import Event, Fault, Start -from ld_eventsource.errors import HTTPStatusError - -from ldclient.impl.aio.concurrency import AsyncTaskRunner -from ldclient.impl.aio.transport import AsyncSSEFactory, make_client_session -from ldclient.impl.datasource.datasource_common import ( - STREAM_ALL_PATH, - StreamClosedError, - parse_path, - require_update_sink -) -from ldclient.impl.retry import ( - FailureKind, - RetryState, - classify_http_status, - for_streaming -) -from ldclient.impl.util import http_error_description, log, monotonic_seconds -from ldclient.interfaces import ( - AsyncDataSourceUpdateSink, - AsyncUpdateProcessor, - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS, VersionedDataKind - - -class AsyncStreamingUpdateProcessor(AsyncUpdateProcessor): - """Reads flag data from LaunchDarkly's streaming endpoint on a background task. - - The SDK owns the delay between connection attempts rather than the SSE - client; see :mod:`ldclient.impl.retry`. - """ - - def __init__(self, config, store, ready, diagnostic_accumulator, sse_factory: Optional[AsyncSSEFactory] = None, retry_state: Optional[RetryState] = None): - self._uri = config.stream_base_uri + STREAM_ALL_PATH - if config.payload_filter_key is not None: - self._uri += '?%s' % parse.urlencode({'filter': config.payload_filter_key}) - self._config = config - self._data_source_update_sink: AsyncDataSourceUpdateSink = require_update_sink(config.data_source_update_sink) - self._store = store - self._running = False - self._ready = ready - self._diagnostic_accumulator = diagnostic_accumulator - # A caller-supplied factory owns whatever session it uses. With no - # factory we build our own session + factory, but that is deferred to - # _run() so the aiohttp ClientSession is created on the running event - # loop rather than at construction time. - self._sse_factory = sse_factory - self._owned_session = None - self._sse: Any = None - self._connection_attempt_started_monotonic: Optional[float] = None - self._runner = AsyncTaskRunner() - self._started = False - self._retry = retry_state or for_streaming(config.initial_reconnect_delay) - self._interrupted_by_sdk = False - - def start(self): - if self._started: - log.info("AsyncStreamingUpdateProcessor has already been started; ignoring") - return - self._started = True - self._runner.spawn("ldclient.datasource.streaming", self._run) - - async def _run(self): - if self._sse_factory is None: - # Build a session from the SDK's HTTP options (CA certs, client cert, - # SSL verification, proxy trust). Build it here, on the running loop, - # as aiohttp requires. The SSE client does not close a supplied - # session, so this data source closes it on teardown. - self._owned_session = make_client_session(self._config) - self._sse_factory = AsyncSSEFactory(self._config, session=self._owned_session) - log.info("Starting AsyncStreamingUpdateProcessor connecting to uri: " + self._uri) - self._running = True - try: - self._sse = self._sse_factory.create(self._uri, self._config.initial_reconnect_delay, sdk_managed_retry=True) - self._connection_attempt_started_monotonic = monotonic_seconds() - async for action in self._sse.all: - if isinstance(action, Start): - # interrupt() is a no-op when the connection has already gone, so - # clear a stale flag here rather than swallow the next real close. - self._interrupted_by_sdk = False - - # On reconnect after an error the timer was cleared; reset it here. - # For the initial connect the pre-loop stamp is already set. - if self._connection_attempt_started_monotonic is None: - self._connection_attempt_started_monotonic = monotonic_seconds() - elif isinstance(action, Event): - message_ok = False - message_handled = False - try: - message_ok = await self._process_message(action) - message_handled = True - except json.decoder.JSONDecodeError as e: - log.info("Error while handling stream event; will restart stream: %s" % e) - await self._interrupt_stream() - - if not await self._handle_error(e): - break - except Exception as e: - log.warning("Error while handling stream event; will restart stream: %s" % e) - await self._interrupt_stream() - - if not await self._handle_error(e): - break - - if message_handled: - self._retry.record_success() - - if message_ok: - self._record_stream_init(False) - self._connection_attempt_started_monotonic = None - - self._data_source_update_sink.update_status(DataSourceState.VALID, None) - - if not self._ready.is_set(): - log.info("AsyncStreamingUpdateProcessor initialized ok.") - self._ready.set() - elif isinstance(action, Fault): - # A Fault with no error is a clean close. An interrupt the - # SDK asked for is not a failure. - if action.error is None: - if self._interrupted_by_sdk: - self._interrupted_by_sdk = False - continue - if not await self._handle_error(StreamClosedError()): - break - continue - - if not await self._handle_error(action.error): - break - finally: - if self._sse: - try: - await self._sse.close() - except Exception as e: - log.warning("Error closing stream connection during shutdown: %s" % e) - await self._close_owned_session() - - async def _close_owned_session(self): - """Close the aiohttp session if the SDK created it. A caller-supplied - factory owns its own session, so ``_owned_session`` is ``None`` and - nothing is closed here. Closing resets the reference to ``None`` so it - isn't closed twice.""" - if self._owned_session is not None: - await self._owned_session.close() - self._owned_session = None - - def _record_stream_init(self, failed: bool): - if self._diagnostic_accumulator and self._connection_attempt_started_monotonic is not None: - current_time = int(time.time() * 1000) - elapsed = int((monotonic_seconds() - self._connection_attempt_started_monotonic) * 1000) - self._diagnostic_accumulator.record_stream_init(current_time, elapsed, failed) - - async def stop(self): - log.info("Stopping AsyncStreamingUpdateProcessor") - self._running = False - - # OFF means an explicit shutdown. No stream failure produces it. It is - # reported before teardown, so a slow close cannot hold back the status - # that tells a waiter to give up. The sink drops anything after OFF. - self._data_source_update_sink.update_status(DataSourceState.OFF, None) - - # Cancel the run task before tearing down the rest, preventing _run from - # starting a fresh SSE connection against the session we are closing. - await self._runner.stop_all() - - if self._sse: - await self._sse.close() - await self._close_owned_session() - - async def _interrupt_stream(self): - """Drops the stream connection so the next read reconnects. The SSE - client reports the close as a Fault with no error, and the flag tells - the loop that this one is ours and is already accounted for.""" - self._interrupted_by_sdk = True - await self._sse.interrupt() - - def initialized(self): - return self._running and self._ready.is_set() is True and self._store.initialized is True - - # Returns True if we initialized the feature store - async def _process_message(self, msg: Event) -> bool: - """Process a single SSE event. Returns True on a successful ``put``.""" - target = self._data_source_update_sink - if msg.event == 'put': - all_data = json.loads(msg.data) - init_data: Mapping[VersionedDataKind, Mapping[str, dict]] = {FEATURES: all_data['data']['flags'], SEGMENTS: all_data['data']['segments']} - log.debug("Received put event with %d flags and %d segments", len(init_data[FEATURES]), len(init_data[SEGMENTS])) - await target.init(init_data) - return True - elif msg.event == 'patch': - payload = json.loads(msg.data) - path = payload['path'] - obj = payload['data'] - log.debug("Received patch event for %s, New version: [%d]", path, obj.get("version")) - parsed = parse_path(path) - if parsed is not None: - await target.upsert(parsed.kind, obj) - else: - log.warning("Patch for unknown path") - elif msg.event == 'delete': - payload = json.loads(msg.data) - path = payload['path'] - # noinspection PyShadowingNames - version = payload['version'] - log.debug("Received delete event for %s, New version: [%d]", path, version) - parsed = parse_path(path) - if parsed is not None: - await target.delete(parsed.kind, parsed.key, version) - else: - log.warning("Delete for unknown path") - else: - log.warning('Unhandled event in stream processor: ' + msg.event) - return False - - # Returns true to continue, false to stop - async def _handle_error(self, error: Exception) -> bool: - """Records a stream failure, reports it, and waits before the retry. - - Returns True once the wait is over, or False if the processor was - stopped. No failure ever ends the stream by itself. The wait is - interrupted by cancelling the task, which matters because the extended - regime can ask for an hour. - """ - if not self._running: - return False # don't retry if we've been deliberately stopped - - self._record_stream_init(True) - - level: Callable[..., None] - - if isinstance(error, json.decoder.JSONDecodeError): - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.INVALID_DATA, 0, time.time(), str(error)) - description = "Unparseable data on stream connection: %s" % error - level = log.error - elif isinstance(error, HTTPStatusError): - kind = classify_http_status(error.status) - error_info = DataSourceErrorInfo(DataSourceErrorKind.ERROR_RESPONSE, error.status, time.time(), str(error)) - description = "Received %s for stream connection" % http_error_description(error.status) - level = log.error if kind is FailureKind.UNEXPECTED else log.warning - elif isinstance(error, StreamClosedError): - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, time.time(), str(error)) - description = "The server closed the stream connection" - level = log.warning - else: - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.UNKNOWN, 0, time.time(), str(error)) - # no stacktrace here because, for a typical connection error, it'll just be a lengthy tour of HTTP client internals - description = "Error on stream connection: %s" % error - level = log.warning - - self._retry.record_failure(kind) - delay = self._retry.next_delay - level("%s - will retry in %.1fs" % (description, delay)) - - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, error_info) - - if delay > 0: - await asyncio.sleep(delay) - - # Set after the wait, so the backoff delay is not counted in the - # stream-init latency we report. - self._connection_attempt_started_monotonic = monotonic_seconds() - return self._running - - # magic methods for "with" statement (used in testing) - async def __aenter__(self): - return self - - async def __aexit__(self, type, value, traceback): - await self.stop() diff --git a/ldclient/impl/datasource/datasource_common.py b/ldclient/impl/datasource/datasource_common.py deleted file mode 100644 index ce65ce29..00000000 --- a/ldclient/impl/datasource/datasource_common.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -Pure helpers shared by the FDv1 polling and streaming data sources. -""" - -# currently excluded from documentation - see docs/README.md - -from collections import namedtuple -from typing import Mapping, Optional, Protocol, TypeVar, runtime_checkable - -from ldclient.impl.util import _LD_ENVID_HEADER -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -STREAM_ALL_PATH = '/all' -FDV1_POLLING_ENDPOINT = '/sdk/latest-all' - -T = TypeVar('T') - -ParsedPath = namedtuple('ParsedPath', ['kind', 'key']) - - -class StreamClosedError(Exception): - """The stream connection closed cleanly, and the SDK did not ask for it. - - The service normally leaves the connection open, so a close the SDK did - not ask for is a connection failure. The SDK backs off before it - reconnects, rather than reconnecting at once. - - It is a NORMAL failure, not an UNEXPECTED one. A load balancer draining - during a rolling deploy closes streams cleanly, and putting that in the - extended regime would take a whole fleet out of service for up to an - hour. - """ - - def __init__(self): - super().__init__("the server closed the stream connection") - - -def require_update_sink(sink: Optional[T]) -> T: - """ - Returns the data source update sink, or raises if it is missing. - - The data system puts the sink on the config before it builds a data - source. A data source writes all its updates to the sink, so it cannot - operate without one. - - :raises ValueError: if the sink is None - """ - if sink is None: - raise ValueError("config.data_source_update_sink is not set. The data system must set it before it builds a data source.") - - return sink - - -@runtime_checkable -class EnvironmentIdSink(Protocol): - """ - Implemented by data source update sinks which can record the environment ID - reported by LaunchDarkly. This is separate from - :class:`ldclient.interfaces.DataSourceUpdateSink` so that externally - implemented sinks remain compatible. - """ - - def set_environment_id(self, environment_id: str) -> None: - ... - - -def record_environment_id(sink, headers: Optional[Mapping[str, str]]): - """ - Records the environment ID from a set of LaunchDarkly response headers, if - both the headers and the sink provide one. - """ - if headers is None or not isinstance(sink, EnvironmentIdSink): - return - - environment_id = headers.get(_LD_ENVID_HEADER) - if isinstance(environment_id, str) and environment_id != '': - sink.set_environment_id(environment_id) - - -def parse_path(path: str): - for kind in [FEATURES, SEGMENTS]: - if path.startswith(kind.stream_api_path): - return ParsedPath(kind=kind, key=path[len(kind.stream_api_path):]) - return None diff --git a/ldclient/impl/datasource/feature_requester.py b/ldclient/impl/datasource/feature_requester.py deleted file mode 100644 index 4dd4e2f0..00000000 --- a/ldclient/impl/datasource/feature_requester.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -Default implementation of feature flag polling requests. -""" - -import json -from collections import namedtuple -from typing import Mapping, Optional, Tuple -from urllib import parse - -import urllib3 - -from ldclient.impl.datasource.datasource_common import FDV1_POLLING_ENDPOINT -from ldclient.impl.http import _http_factory -from ldclient.impl.util import _headers, log, throw_if_unsuccessful_response -from ldclient.interfaces import FeatureRequester -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -CacheEntry = namedtuple('CacheEntry', ['data', 'etag']) - - -class FeatureRequesterImpl(FeatureRequester): - def __init__(self, config): - self._cache = dict() - self._http = _http_factory(config).create_pool_manager(1, config.base_uri) - self._config = config - self._poll_uri = config.base_uri + FDV1_POLLING_ENDPOINT - if config.payload_filter_key is not None: - self._poll_uri += '?%s' % parse.urlencode({'filter': config.payload_filter_key}) - - def get_all_data(self): - (data, _) = self.get_all_data_with_headers() - return data - - def get_all_data_with_headers(self) -> Tuple[dict, Optional[Mapping[str, str]]]: - uri = self._poll_uri - hdrs = _headers(self._config) - cache_entry = self._cache.get(uri) - hdrs['Accept-Encoding'] = 'gzip' - if cache_entry is not None: - hdrs['If-None-Match'] = cache_entry.etag - r = self._http.request('GET', uri, headers=hdrs, timeout=urllib3.Timeout(connect=self._config.http.connect_timeout, read=self._config.http.read_timeout), retries=1) - throw_if_unsuccessful_response(r) - if r.status == 304 and cache_entry is not None: - data = cache_entry.data - etag = cache_entry.etag - from_cache = True - else: - data = json.loads(r.data.decode('UTF-8')) - etag = r.headers.get('ETag') - from_cache = False - if etag is not None: - self._cache[uri] = CacheEntry(data=data, etag=etag) - log.debug("%s response status:[%d] From cache? [%s] ETag:[%s]", uri, r.status, from_cache, etag) - - return ({FEATURES: data['flags'], SEGMENTS: data['segments']}, r.headers) diff --git a/ldclient/impl/datasource/polling.py b/ldclient/impl/datasource/polling.py deleted file mode 100644 index 3fb9fcc1..00000000 --- a/ldclient/impl/datasource/polling.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -Default implementation of the polling component. -""" - -# currently excluded from documentation - see docs/README.md - -import time -from threading import Event -from typing import Any, Mapping, Optional, Protocol, Tuple, runtime_checkable - -from ldclient.config import Config -from ldclient.impl.datasource.datasource_common import ( - record_environment_id, - require_update_sink -) -from ldclient.impl.repeating_task import RepeatingTask -from ldclient.impl.retry import ( - FailureKind, - RetryState, - classify_http_status, - for_polling -) -from ldclient.impl.util import ( - UnsuccessfulResponseException, - http_error_description, - log -) -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceUpdateSink, - FeatureRequester, - FeatureStore, - UpdateProcessor -) - - -@runtime_checkable -class _FeatureRequesterWithHeaders(Protocol): - def get_all_data_with_headers(self) -> Tuple[Any, Optional[Mapping[str, str]]]: - ... - - -class PollingUpdateProcessor(UpdateProcessor): - """Polls LaunchDarkly for flag data on its own worker thread. - - The task reads its wait from the retry state, which ``_poll`` updates, so a - failure can push the next poll further out than the poll interval. See - :mod:`ldclient.impl.retry`. - """ - - def __init__(self, config: Config, requester: FeatureRequester, store: FeatureStore, ready: Event, retry_state: Optional[RetryState] = None): - self._config = config - self._data_source_update_sink: DataSourceUpdateSink = require_update_sink(config.data_source_update_sink) - self._requester = requester - self._store = store - self._ready = ready - self._retry = retry_state or for_polling(config.poll_interval) - self._task = RepeatingTask("ldclient.datasource.polling", self._retry, 0, self._poll) - - def start(self): - log.info("Starting PollingUpdateProcessor with request interval: " + str(self._config.poll_interval)) - self._task.start() - - def initialized(self): - return self._ready.is_set() is True and self._store.initialized is True - - def stop(self): - log.info("Stopping PollingUpdateProcessor") - self._task.stop() - self._data_source_update_sink.update_status(DataSourceState.OFF, None) - - def _poll(self) -> None: - """Makes one poll request and records the outcome on the retry state.""" - try: - (all_data, headers) = self._get_all_data_with_headers() - record_environment_id(self._data_source_update_sink, headers) - self._data_source_update_sink.init(all_data) - self._data_source_update_sink.update_status(DataSourceState.VALID, None) - - # Report the status before signaling readiness, so a caller that - # wakes on readiness cannot still read INITIALIZING. - if not self._ready.is_set() and self._store.initialized: - log.info("PollingUpdateProcessor initialized ok") - self._ready.set() - - self._retry.record_success() - return - except UnsuccessfulResponseException as e: - kind = classify_http_status(e.status) - error_info = DataSourceErrorInfo(DataSourceErrorKind.ERROR_RESPONSE, e.status, time.time(), str(e)) - description = "Received %s for polling request" % http_error_description(e.status) - level = log.error if kind is FailureKind.UNEXPECTED else log.warning - stacktrace = None - except Exception as e: - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.UNKNOWN, 0, time.time(), str(e)) - description = "Error encountered when updating flags: %s" % e - level = log.error - # The exception is passed explicitly: by the time the message is - # logged, the handler has exited and exc_info() is empty. - stacktrace = e - - self._retry.record_failure(kind) - delay = self._retry.next_delay - level("%s - will retry in %.1fs" % (description, delay), exc_info=stacktrace) - - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, error_info) - - def _get_all_data_with_headers(self) -> Tuple[Any, Optional[Mapping[str, str]]]: - """ - Externally provided feature requesters are not required to surface - response headers, so fall back to the data-only method. - """ - if isinstance(self._requester, _FeatureRequesterWithHeaders): - return self._requester.get_all_data_with_headers() - - return (self._requester.get_all_data(), None) diff --git a/ldclient/impl/datasource/status.py b/ldclient/impl/datasource/status.py deleted file mode 100644 index fbe761bd..00000000 --- a/ldclient/impl/datasource/status.py +++ /dev/null @@ -1,176 +0,0 @@ -import time -from typing import Any, Callable, Mapping, Optional, Protocol, Set - -from ldclient.impl.dependency_tracker import DependencyTracker, KindAndKey -from ldclient.impl.listeners import Listeners -from ldclient.impl.rwlock import ReadWriteLock -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceStatus, - DataSourceStatusProvider, - DataSourceUpdateSink, - FeatureStore, - FlagChange -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS, VersionedDataKind - - -class DataSourceUpdateSinkImpl(DataSourceUpdateSink): - def __init__(self, store: FeatureStore, status_listeners: Listeners, flag_change_listeners: Listeners): - self.__store = store - self.__status_listeners = status_listeners - self.__flag_change_listeners = flag_change_listeners - self.__tracker = DependencyTracker() - - self.__lock = ReadWriteLock() - self.__status = DataSourceStatus(DataSourceState.INITIALIZING, time.time(), None) - self.__environment_id: Optional[str] = None - - @property - def status(self) -> DataSourceStatus: - with self.__lock.read(): - return self.__status - - @property - def environment_id(self) -> Optional[str]: - with self.__lock.read(): - return self.__environment_id - - def set_environment_id(self, environment_id: str) -> None: - with self.__lock.write(): - self.__environment_id = environment_id - - def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]): - old_data = None - - def init_store(): - nonlocal old_data - if self.__flag_change_listeners.has_listeners(): - old_data = {} - for kind in [FEATURES, SEGMENTS]: - old_data[kind] = self.__store.all(kind, lambda x: x) - - self.__store.init(all_data) - - self.__monitor_store_update(init_store) - self.__reset_tracker_with_new_data(all_data) - - if old_data is None: - return - - self.__send_change_events(self.__compute_changed_items_for_full_data_set(old_data, all_data)) - - def upsert(self, kind: VersionedDataKind, item: dict): - updated = self.__monitor_store_update(lambda: self.__store.upsert(kind, item)) - - # Update dependencies and send change events only if the store applied the write. - # A rejected write does not change the stored data. - if updated: - key = item.get('key', '') - self.__update_dependency_for_single_item(kind, key, item) - - def delete(self, kind: VersionedDataKind, key: str, version: int): - deleted = self.__monitor_store_update(lambda: self.__store.delete(kind, key, version)) - - # Update dependencies and send change events only if the store applied the delete. - if deleted: - self.__update_dependency_for_single_item(kind, key, None) - - def update_status(self, new_state: DataSourceState, new_error: Optional[DataSourceErrorInfo]): - status_to_broadcast = None - - with self.__lock.write(): - old_status = self.__status - - # OFF is terminal. A poll or stream connection that was still in - # flight when the data source stopped must not report after it. - if old_status.state == DataSourceState.OFF: - return - - if new_state == DataSourceState.INTERRUPTED and old_status.state == DataSourceState.INITIALIZING: - new_state = DataSourceState.INITIALIZING - - if new_state == old_status.state and new_error is None: - return - - self.__status = DataSourceStatus(new_state, self.__status.since if new_state == self.__status.state else time.time(), self.__status.error if new_error is None else new_error) - - status_to_broadcast = self.__status - - if status_to_broadcast is not None: - self.__status_listeners.notify(status_to_broadcast) - - def __monitor_store_update(self, fn: Callable[[], Any]) -> Any: - try: - return fn() - except Exception as e: - error_info = DataSourceErrorInfo(DataSourceErrorKind.STORE_ERROR, 0, time.time(), str(e)) - self.update_status(DataSourceState.INTERRUPTED, error_info) - raise - - def __update_dependency_for_single_item(self, kind: VersionedDataKind, key: str, item: Optional[dict]): - self.__tracker.update_dependencies_from(kind, key, item) - if self.__flag_change_listeners.has_listeners(): - affected_items: Set[KindAndKey] = set() - self.__tracker.add_affected_items(affected_items, KindAndKey(kind=kind, key=key)) - self.__send_change_events(affected_items) - - def __reset_tracker_with_new_data(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]): - self.__tracker.reset() - - for kind, items in all_data.items(): - for key, item in items.items(): - self.__tracker.update_dependencies_from(kind, key, item) - - def __send_change_events(self, affected_items: Set[KindAndKey]): - for item in affected_items: - if item.kind == FEATURES: - self.__flag_change_listeners.notify(FlagChange(item.key)) - - def __compute_changed_items_for_full_data_set(self, old_data: Mapping[VersionedDataKind, Mapping[str, dict]], new_data: Mapping[VersionedDataKind, Mapping[str, dict]]): - affected_items: Set[KindAndKey] = set() - - for kind in [FEATURES, SEGMENTS]: - old_items = old_data.get(kind, {}) - new_items = new_data.get(kind, {}) - - keys: Set[str] = set() - - for key in keys.union(old_items.keys(), new_items.keys()): - old_item = old_items.get(key) - new_item = new_items.get(key) - - if old_item is None and new_item is None: - continue - - if old_item is None or new_item is None or old_item['version'] < new_item['version']: - self.__tracker.add_affected_items(affected_items, KindAndKey(kind=kind, key=key)) - - return affected_items - - -class _DataSourceStatusSource(Protocol): - """The status property a status provider reads from its update sink; - satisfied by both the sync and async sink implementations.""" - - @property - def status(self) -> DataSourceStatus: - ... - - -class DataSourceStatusProviderImpl(DataSourceStatusProvider): - def __init__(self, listeners: Listeners, update_sink: _DataSourceStatusSource): - self.__listeners = listeners - self.__update_sink = update_sink - - @property - def status(self) -> DataSourceStatus: - return self.__update_sink.status - - def add_listener(self, listener: Callable[[DataSourceStatus], None]): - self.__listeners.add(listener) - - def remove_listener(self, listener: Callable[[DataSourceStatus], None]): - self.__listeners.remove(listener) diff --git a/ldclient/impl/datasource/streaming.py b/ldclient/impl/datasource/streaming.py deleted file mode 100644 index e9c30509..00000000 --- a/ldclient/impl/datasource/streaming.py +++ /dev/null @@ -1,272 +0,0 @@ -import json -import time -from threading import TIMEOUT_MAX -from threading import Event as ThreadEvent -from threading import Thread -from typing import Callable, Optional -from urllib import parse - -from ld_eventsource import SSEClient -from ld_eventsource.actions import Event, Fault, Start -from ld_eventsource.config import ( - ConnectStrategy, - ErrorStrategy, - RetryDelayStrategy -) -from ld_eventsource.errors import HTTPStatusError - -from ldclient.impl.datasource.datasource_common import ( - STREAM_ALL_PATH, - StreamClosedError, - parse_path, - record_environment_id, - require_update_sink -) -from ldclient.impl.http import HTTPFactory, _http_factory -from ldclient.impl.retry import ( - FailureKind, - RetryState, - classify_http_status, - for_streaming -) -from ldclient.impl.util import http_error_description, log, monotonic_seconds -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceUpdateSink, - UpdateProcessor -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -# allows for up to 5 minutes to elapse without any data sent across the stream. The heartbeats sent as comments on the -# stream will keep this from triggering -stream_read_timeout = 5 * 60 - - -class StreamingUpdateProcessor(Thread, UpdateProcessor): - """Reads flag data from LaunchDarkly's streaming endpoint on its own thread. - - The SDK owns the delay between connection attempts rather than the SSE - client; see :meth:`_create_sse_client` and :mod:`ldclient.impl.retry`. - """ - - def __init__(self, config, store, ready, diagnostic_accumulator, retry_state: Optional[RetryState] = None): - Thread.__init__(self, name="ldclient.datasource.streaming") - self.daemon = True - self._uri = config.stream_base_uri + STREAM_ALL_PATH - if config.payload_filter_key is not None: - self._uri += '?%s' % parse.urlencode({'filter': config.payload_filter_key}) - self._config = config - self._data_source_update_sink: DataSourceUpdateSink = require_update_sink(config.data_source_update_sink) - self._store = store - self._running = False - self._ready = ready - self._diagnostic_accumulator = diagnostic_accumulator - self._connection_attempt_started_monotonic: Optional[float] = None - self._retry = retry_state or for_streaming(config.initial_reconnect_delay) - self._sse: Optional[SSEClient] = None - self._stop_event = ThreadEvent() - self._interrupted_by_sdk = False - - def run(self): - log.info("Starting StreamingUpdateProcessor connecting to uri: " + self._uri) - self._running = True - self._sse = self._create_sse_client() - - # stop() may have run before the client existed, in which case it had - # nothing to close. Never read a connection nobody is left to close. - if self._stop_event.is_set(): - self._sse.close() - return - - self._connection_attempt_started_monotonic = monotonic_seconds() - try: - for action in self._sse.all: - if isinstance(action, Start): - # interrupt() is a no-op when the connection has already gone, so - # clear a stale flag here rather than swallow the next real close. - self._interrupted_by_sdk = False - record_environment_id(self._data_source_update_sink, action.headers) - elif isinstance(action, Event): - message_ok = False - message_handled = False - try: - message_ok = self._process_message(self._data_source_update_sink, action) - message_handled = True - except json.decoder.JSONDecodeError as e: - log.info("Error while handling stream event; will restart stream: %s" % e) - self._interrupt_stream() - - if not self._handle_error(e): - break - except Exception as e: - log.info("Error while handling stream event; will restart stream: %s" % e) - self._interrupt_stream() - - if not self._handle_error(e): - break - - if message_handled: - self._retry.record_success() - - if message_ok: - self._record_stream_init(False) - self._connection_attempt_started_monotonic = None - - self._data_source_update_sink.update_status(DataSourceState.VALID, None) - - if not self._ready.is_set(): - log.info("StreamingUpdateProcessor initialized ok.") - self._ready.set() - elif isinstance(action, Fault): - # A Fault with no error is a clean close. An interrupt the SDK - # asked for is not a failure. - if action.error is None: - if self._interrupted_by_sdk: - self._interrupted_by_sdk = False - continue - if not self._handle_error(StreamClosedError()): - break - continue - - if not self._handle_error(action.error): - break - finally: - # A raise inside the loop must not leak the connection pool. - self._sse.close() - - def _record_stream_init(self, failed: bool): - if self._diagnostic_accumulator and self._connection_attempt_started_monotonic is not None: - current_time = int(time.time() * 1000) - elapsed = int((monotonic_seconds() - self._connection_attempt_started_monotonic) * 1000) - self._diagnostic_accumulator.record_stream_init(current_time, elapsed, failed) - - def _create_sse_client(self) -> SSEClient: - # We don't want the stream to use the same read timeout as the rest of the SDK. - http_factory = _http_factory(self._config) - stream_http_factory = HTTPFactory(http_factory.base_headers, http_factory.http_config, override_read_timeout=stream_read_timeout) - return SSEClient( - connect=ConnectStrategy.http( - url=self._uri, headers=http_factory.base_headers, pool=stream_http_factory.create_pool_manager(1, self._uri), urllib3_request_options={"timeout": stream_http_factory.timeout} - ), - error_strategy=ErrorStrategy.always_continue(), # we'll make error-handling decisions when we see a Fault - # The SSE client's retry is disabled; the SDK owns the delay. The base - # strategy must be passed: omitting it selects the library's backoff. - initial_retry_delay=0, - retry_delay_strategy=RetryDelayStrategy(), - retry_delay_reset_threshold=0, - logger=log, - ) - - def stop(self): - log.info("Stopping StreamingUpdateProcessor") - self._running = False - self._stop_event.set() - - # OFF means an explicit shutdown. No stream failure produces it. It is - # reported before teardown, so a slow close cannot hold back the status - # that tells a waiter to give up. The sink drops anything after OFF. - self._data_source_update_sink.update_status(DataSourceState.OFF, None) - - if self._sse: - self._sse.close() - - def _interrupt_stream(self): - """Drops the stream connection so the next read reconnects. The SSE - client reports the close as a Fault with no error, and the flag tells - the loop that this one is ours and is already accounted for.""" - self._interrupted_by_sdk = True - self._sse.interrupt() - - def initialized(self): - return self._running and self._ready.is_set() is True and self._store.initialized is True - - # Returns True if we initialized the feature store - def _process_message(self, store, msg: Event) -> bool: - if msg.event == 'put': - all_data = json.loads(msg.data) - init_data = {FEATURES: all_data['data']['flags'], SEGMENTS: all_data['data']['segments']} - log.debug("Received put event with %d flags and %d segments", len(init_data[FEATURES]), len(init_data[SEGMENTS])) - store.init(init_data) - return True - elif msg.event == 'patch': - payload = json.loads(msg.data) - path = payload['path'] - obj = payload['data'] - log.debug("Received patch event for %s, New version: [%d]", path, obj.get("version")) - target = parse_path(path) - if target is not None: - store.upsert(target.kind, obj) - else: - log.warning("Patch for unknown path") - elif msg.event == 'delete': - payload = json.loads(msg.data) - path = payload['path'] - # noinspection PyShadowingNames - version = payload['version'] - log.debug("Received delete event for %s, New version: [%d]", path, version) - target = parse_path(path) - if target is not None: - store.delete(target.kind, target.key, version) - else: - log.warning("Delete for unknown path") - else: - log.warning('Unhandled event in stream processor: ' + msg.event) - return False - - # Returns true to continue, false to stop - def _handle_error(self, error: Exception) -> bool: - """Records a stream failure, reports it, and waits before the retry. - - Returns True once the wait is over, or False if the processor was - stopped. No failure ever ends the stream by itself. - """ - if not self._running: - return False # don't retry if we've been deliberately stopped - - self._record_stream_init(True) - - level: Callable[..., None] - - if isinstance(error, json.decoder.JSONDecodeError): - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.INVALID_DATA, 0, time.time(), str(error)) - description = "Unparseable data on stream connection: %s" % error - level = log.error - elif isinstance(error, HTTPStatusError): - kind = classify_http_status(error.status) - error_info = DataSourceErrorInfo(DataSourceErrorKind.ERROR_RESPONSE, error.status, time.time(), str(error)) - description = "Received %s for stream connection" % http_error_description(error.status) - level = log.error if kind is FailureKind.UNEXPECTED else log.warning - elif isinstance(error, StreamClosedError): - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, time.time(), str(error)) - description = "The server closed the stream connection" - level = log.warning - else: - kind = FailureKind.NORMAL - error_info = DataSourceErrorInfo(DataSourceErrorKind.UNKNOWN, 0, time.time(), str(error)) - # no stacktrace here because, for a typical connection error, it'll just be a lengthy tour of urllib3 internals - description = "Error on stream connection: %s" % error - level = log.warning - - self._retry.record_failure(kind) - delay = self._retry.next_delay - level("%s - will retry in %.1fs" % (description, delay)) - - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, error_info) - - interrupted = self._stop_event.wait(min(delay, TIMEOUT_MAX)) - - # Set after the wait, so the backoff delay is not counted in the - # stream-init latency we report. - self._connection_attempt_started_monotonic = monotonic_seconds() - return not interrupted - - # magic methods for "with" statement (used in testing) - def __enter__(self): - return self - - def __exit__(self, type, value, traceback): - self.stop() diff --git a/ldclient/impl/datasourcev2/async_polling.py b/ldclient/impl/datasourcev2/async_polling.py index b6f8fbe2..5c15b231 100644 --- a/ldclient/impl/datasourcev2/async_polling.py +++ b/ldclient/impl/datasourcev2/async_polling.py @@ -17,10 +17,8 @@ ) from ldclient.impl.aio.concurrency import AsyncEvent from ldclient.impl.aio.transport import AsyncHTTPTransport -from ldclient.impl.datasource.async_feature_requester import ( - FDV1_POLLING_ENDPOINT -) from ldclient.impl.datasourcev2.polling_common import ( + FDV1_POLLING_ENDPOINT, PollAction, fdv1_polling_payload_to_changeset, map_polling_result, diff --git a/ldclient/impl/datasourcev2/async_streaming.py b/ldclient/impl/datasourcev2/async_streaming.py index 4d117ea8..c4fb51a7 100644 --- a/ldclient/impl/datasourcev2/async_streaming.py +++ b/ldclient/impl/datasourcev2/async_streaming.py @@ -241,7 +241,7 @@ async def stop(self): """ Stops the streaming synchronizer, closing any open connections. """ - log.info("Stopping StreamingUpdateProcessor") + log.info("Stopping StreamingDataSourceV2 synchronizer") self._running = False if self._sse: await self._sse.close() diff --git a/ldclient/impl/datasourcev2/polling.py b/ldclient/impl/datasourcev2/polling.py index a51238e9..897c3c6d 100644 --- a/ldclient/impl/datasourcev2/polling.py +++ b/ldclient/impl/datasourcev2/polling.py @@ -18,8 +18,8 @@ DataSourceBuilderConfig, HTTPConfig ) -from ldclient.impl.datasource.feature_requester import FDV1_POLLING_ENDPOINT from ldclient.impl.datasourcev2.polling_common import ( + FDV1_POLLING_ENDPOINT, PollAction, fdv1_polling_payload_to_changeset, map_polling_result, diff --git a/ldclient/impl/datasourcev2/polling_common.py b/ldclient/impl/datasourcev2/polling_common.py index 5abf8cd4..a1a40a59 100644 --- a/ldclient/impl/datasourcev2/polling_common.py +++ b/ldclient/impl/datasourcev2/polling_common.py @@ -40,6 +40,9 @@ Update ) +# The FDv1 fallback synchronizer polls this endpoint. +FDV1_POLLING_ENDPOINT = '/sdk/latest-all' + # pylint: disable=too-many-branches,too-many-return-statements def polling_payload_to_changeset(data: dict) -> _Result[ChangeSet, str]: diff --git a/ldclient/impl/datasourcev2/streaming.py b/ldclient/impl/datasourcev2/streaming.py index f896d405..0821973b 100644 --- a/ldclient/impl/datasourcev2/streaming.py +++ b/ldclient/impl/datasourcev2/streaming.py @@ -249,7 +249,7 @@ def stop(self): """ Stops the streaming synchronizer, closing any open connections. """ - log.info("Stopping StreamingUpdateProcessor") + log.info("Stopping StreamingDataSourceV2 synchronizer") self._running = False if self._sse: self._sse.close() diff --git a/ldclient/impl/datastore/__init__.py b/ldclient/impl/datastore/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/ldclient/impl/datastore/status.py b/ldclient/impl/datastore/status.py deleted file mode 100644 index 989e3215..00000000 --- a/ldclient/impl/datastore/status.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import annotations - -from copy import copy -from typing import TYPE_CHECKING, Callable, Protocol - -from ldclient.impl.listeners import Listeners -from ldclient.impl.rwlock import ReadWriteLock -from ldclient.interfaces import ( - DataStoreStatus, - DataStoreStatusProvider, - DataStoreUpdateSink -) - -if TYPE_CHECKING: - from ldclient.impl.datasystem.fdv1 import _FeatureStoreClientWrapper - - -class DataStoreUpdateSinkImpl(DataStoreUpdateSink): - def __init__(self, listeners: Listeners): - self.__listeners = listeners - - self.__lock = ReadWriteLock() - self.__status = DataStoreStatus(True, False) - - @property - def listeners(self) -> Listeners: - return self.__listeners - - def status(self) -> DataStoreStatus: - with self.__lock.read(): - return copy(self.__status) - - def update_status(self, status: DataStoreStatus): - with self.__lock.write(): - old_value, self.__status = self.__status, status - - if old_value != status: - self.__listeners.notify(status) - - -class DataStoreStatusProviderImpl(DataStoreStatusProvider): - def __init__(self, store: _FeatureStoreClientWrapper, update_sink: DataStoreUpdateSinkImpl): - self.__store = store - self.__update_sink = update_sink - - @property - def status(self) -> DataStoreStatus: - return self.__update_sink.status() - - def is_monitoring_enabled(self) -> bool: - return self.__store.is_monitoring_enabled() - - def add_listener(self, listener: Callable[[DataStoreStatus], None]): - self.__update_sink.listeners.add(listener) - - def remove_listener(self, listener: Callable[[DataStoreStatus], None]): - self.__update_sink.listeners.remove(listener) diff --git a/ldclient/impl/datasystem/__init__.py b/ldclient/impl/datasystem/__init__.py index 26be520d..ef313b13 100644 --- a/ldclient/impl/datasystem/__init__.py +++ b/ldclient/impl/datasystem/__init__.py @@ -1,6 +1,6 @@ """ -This package contains the generic interfaces used for the data system (v1 and -v2), as well as types for v1 and v2 specific protocols. +This package contains the interfaces for the data system, and the types for +the FDv2 protocol. """ from abc import abstractmethod diff --git a/ldclient/impl/datasystem/async_fdv1.py b/ldclient/impl/datasystem/async_fdv1.py deleted file mode 100644 index ed5fc86b..00000000 --- a/ldclient/impl/datasystem/async_fdv1.py +++ /dev/null @@ -1,199 +0,0 @@ -from typing import Any, Callable, Dict, Optional - -from ldclient.async_config import AsyncConfig -from ldclient.impl.aio.concurrency import AsyncEvent -from ldclient.impl.aio.transport import AsyncHTTPTransport, AsyncSSEFactory -from ldclient.impl.datasource.async_feature_requester import ( - AsyncFeatureRequesterImpl -) -from ldclient.impl.datasource.async_polling import AsyncPollingUpdateProcessor -from ldclient.impl.datasource.async_status import AsyncDataSourceUpdateSinkImpl -from ldclient.impl.datasource.async_streaming import ( - AsyncStreamingUpdateProcessor -) -from ldclient.impl.datasource.status import DataSourceStatusProviderImpl -from ldclient.impl.datastore.status import ( - DataStoreStatusProviderImpl, - DataStoreUpdateSinkImpl -) -from ldclient.impl.datasystem import ( - AsyncDataSystem, - DataAvailability, - DiagnosticAccumulator -) -from ldclient.impl.datasystem.store import _decode -from ldclient.impl.listeners import Listeners -from ldclient.impl.stubs import AsyncNullUpdateProcessor -from ldclient.impl.util import log -from ldclient.interfaces import ( - AsyncFeatureStore, - AsyncReadOnlyStore, - AsyncUpdateProcessor, - DataSourceStatusProvider, - DataStoreStatusProvider -) -from ldclient.versioned_data_kind import VersionedDataKind - - -class _AsyncReadOnlyFeatureStoreView(AsyncReadOnlyStore): - """Read-only view of an async feature store. - - Serves every read from the wrapped store. Items that a custom feature store - keeps as raw dicts are decoded into model objects; items that are already - models pass through unchanged. - """ - - def __init__(self, store: AsyncReadOnlyStore): - self._store = store - - async def get(self, kind: VersionedDataKind, key: str) -> Optional[Any]: - return _decode(kind, await self._store.get(kind, key)) - - async def all(self, kind: VersionedDataKind) -> Dict[str, Any]: - result = await self._store.all(kind) - return {key: _decode(kind, item) for key, item in result.items()} - - -class AsyncFDv1(AsyncDataSystem): - """ - AsyncFDv1 provides the v1 data source and store behavior through the - AsyncDataSystem interface. It is the async version of - :class:`ldclient.impl.datasystem.fdv1.FDv1`. Unlike the sync side, it uses - the feature store directly and does not wrap it for persistent-store status - monitoring. - """ - - def __init__(self, config: AsyncConfig, store: AsyncFeatureStore, session_provider: Callable[[], Any]): - self._config = config - self._store = store - self._store_view = _AsyncReadOnlyFeatureStoreView(store) - # The client creates the aiohttp session lazily inside the loop; the data - # source resolves it here when it builds its network processor at start(). - self._session_provider = session_provider - - # Set up data store status tracking (no store wrapper) - self._data_store_listeners = Listeners() - self._data_store_update_sink = DataStoreUpdateSinkImpl( - self._data_store_listeners - ) - # The provider only calls the store's monitoring methods, which the async - # store also has, so the sync-typed signature is fine. - self._data_store_status_provider_impl = DataStoreStatusProviderImpl( - self._store, self._data_store_update_sink # type: ignore[arg-type] - ) - - # Set up the data source status tracking and listeners - self._data_source_listeners = Listeners() - self._flag_change_listeners = Listeners() - self._data_source_update_sink = AsyncDataSourceUpdateSinkImpl( - self._store, - self._data_source_listeners, - self._flag_change_listeners, - ) - self._data_source_status_provider_impl = DataSourceStatusProviderImpl( - self._data_source_listeners, self._data_source_update_sink - ) - - # v1 processors read the sink from the config for status updates. The config - # attribute is typed as the sync sink, but the async sink has the same methods. - self._config._data_source_update_sink = self._data_source_update_sink # type: ignore[assignment] - - # Update processor created in start(), because it needs the ready event - self._update_processor: Optional[AsyncUpdateProcessor] = None - - # Diagnostic accumulator provided by client for streaming metrics - self._diagnostic_accumulator: Optional[DiagnosticAccumulator] = None - - def start(self, set_on_ready: AsyncEvent): - """ - Starts the v1 update processor and returns immediately. The provided - event is set by the processor upon first successful initialization or - upon permanent failure. - """ - update_processor = self._make_update_processor( - self._config, self._store, set_on_ready - ) - self._update_processor = update_processor - update_processor.start() - - async def stop(self): - if self._update_processor is not None: - await self._update_processor.stop() - await self._store.close() - - @property - def store(self) -> AsyncReadOnlyStore: - return self._store_view - - def set_diagnostic_accumulator(self, diagnostic_accumulator: DiagnosticAccumulator): - """ - Sets the diagnostic accumulator for streaming initialization metrics. - This should be called before start() to ensure metrics are collected. - """ - self._diagnostic_accumulator = diagnostic_accumulator - - @property - def data_source_status_provider(self) -> DataSourceStatusProvider: - return self._data_source_status_provider_impl - - @property - def data_store_status_provider(self) -> DataStoreStatusProvider: - return self._data_store_status_provider_impl - - @property - def flag_change_listeners(self) -> Listeners: - return self._flag_change_listeners - - async def data_availability(self) -> DataAvailability: - if self._config.offline: - return DataAvailability.DEFAULTS - - if self._update_processor is not None and self._update_processor.initialized(): - return DataAvailability.REFRESHED - - # Awaits the store so a persistent store populated by another process is - # recognized. A persistent-store error is logged and reported as no data. - try: - ready = await self._store.is_initialized() - except Exception as e: - log.warning("Error checking persistent store readiness: %s", e) - return DataAvailability.DEFAULTS - - return DataAvailability.CACHED if ready else DataAvailability.DEFAULTS - - @property - def target_availability(self) -> DataAvailability: - if self._config.offline: - return DataAvailability.DEFAULTS - # In LDD mode or normal connected modes, the ideal is to be refreshed - return DataAvailability.REFRESHED - - def _make_update_processor(self, config: AsyncConfig, store: AsyncFeatureStore, ready: AsyncEvent): - # Mirrors FDv1._make_update_processor but builds the async processors - if config.update_processor_class: - log.info("Using user-specified update processor: " + str(config.update_processor_class)) - return config.update_processor_class(config, store, ready) - - if config.offline or config.use_ldd: - return AsyncNullUpdateProcessor(config, store, ready) - - if config.stream: - return AsyncStreamingUpdateProcessor( - config, - store, - ready, - self._diagnostic_accumulator, - AsyncSSEFactory(config, session=self._session_provider(), proxy=config.http.http_proxy), - ) - - log.info("Disabling streaming API") - log.warning("You should only disable the streaming API if instructed to do so by LaunchDarkly support") - - if config.feature_requester_class: - feature_requester = config.feature_requester_class(config) - else: - feature_requester = AsyncFeatureRequesterImpl( - config, - AsyncHTTPTransport(config, client=self._session_provider()), - ) - return AsyncPollingUpdateProcessor(config, feature_requester, store, ready) diff --git a/ldclient/impl/datasystem/async_fdv2.py b/ldclient/impl/datasystem/async_fdv2.py index 80d06ec7..e4cc51ea 100644 --- a/ldclient/impl/datasystem/async_fdv2.py +++ b/ldclient/impl/datasystem/async_fdv2.py @@ -241,9 +241,6 @@ def __init__( self._config = config self._data_system_config = data_system_config - if config.payload_filter_key is not None: - log.warning("Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests") - self._synchronizers: List[DataSourceBuilder[AsyncSynchronizer]] = list(data_system_config.synchronizers) if data_system_config.synchronizers else [] self._fdv1_fallback_synchronizer_builder = data_system_config.fdv1_fallback_synchronizer self._disabled = config.offline diff --git a/ldclient/impl/datasystem/fdv1.py b/ldclient/impl/datasystem/fdv1.py deleted file mode 100644 index aac7d6c2..00000000 --- a/ldclient/impl/datasystem/fdv1.py +++ /dev/null @@ -1,310 +0,0 @@ -from threading import Event, Lock -from typing import Any, Callable, Dict, Mapping, Optional - -from ldclient.config import Config -from ldclient.feature_store import _FeatureStoreDataSetSorter -from ldclient.impl.datasource.feature_requester import FeatureRequesterImpl -from ldclient.impl.datasource.polling import PollingUpdateProcessor -from ldclient.impl.datasource.status import ( - DataSourceStatusProviderImpl, - DataSourceUpdateSinkImpl -) -from ldclient.impl.datasource.streaming import StreamingUpdateProcessor -from ldclient.impl.datastore.status import ( - DataStoreStatusProviderImpl, - DataStoreUpdateSinkImpl -) -from ldclient.impl.datasystem import ( - DataAvailability, - DataSystem, - DiagnosticAccumulator -) -from ldclient.impl.datasystem.store import _decode -from ldclient.impl.listeners import Listeners -from ldclient.impl.repeating_task import RepeatingTask -from ldclient.impl.rwlock import ReadWriteLock -from ldclient.impl.stubs import NullUpdateProcessor -from ldclient.impl.util import log -from ldclient.interfaces import ( - DataSourceStatusProvider, - DataStoreStatus, - DataStoreStatusProvider, - DataStoreUpdateSink, - FeatureStore, - ReadOnlyStore, - UpdateProcessor -) -from ldclient.versioned_data_kind import VersionedDataKind - - -class _FeatureStoreClientWrapper(FeatureStore): - """Provides additional behavior that the client requires before or after feature store operations. - Currently this just means sorting the data set for init() and dealing with data store status listeners. - """ - - def __init__(self, store: FeatureStore, store_update_sink: DataStoreUpdateSink): - self.store = store - self.__store_update_sink = store_update_sink - self.__monitoring_enabled = self.is_monitoring_enabled() - - # Held for each write and by close(). A write that starts after - # close() does nothing, and close() waits for a write in progress. - self.__write_lock = Lock() - - # Covers the following variables - self.__lock = ReadWriteLock() - self.__last_available = True - self.__poller: Optional[RepeatingTask] = None - self.__closed = False - - def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, Dict[Any, Any]]]): - self.__write(lambda: self.store.init(_FeatureStoreDataSetSorter.sort_all_collections(all_data)), None) - - def get(self, kind, key, callback): - return self.__wrapper(lambda: self.store.get(kind, key, callback)) - - def all(self, kind, callback): - return self.__wrapper(lambda: self.store.all(kind, callback)) - - def delete(self, kind, key, version) -> bool: - return self.__write(lambda: self.store.delete(kind, key, version), False) - - def upsert(self, kind, item) -> bool: - return self.__write(lambda: self.store.upsert(kind, item), False) - - @property - def initialized(self) -> bool: - return self.store.initialized - - def __wrapper(self, fn: Callable): - try: - return fn() - except BaseException: - if self.__monitoring_enabled: - self.__update_availability(False) - raise - - def __write(self, fn: Callable, result_if_closed: Any): - # The failure is reported after the lock is released. A status listener can then - # write or close the client without a deadlock. - try: - with self.__write_lock: - if self.__closed: - return result_if_closed - return fn() - except BaseException: - if self.__monitoring_enabled: - self.__update_availability(False) - raise - - def __update_availability(self, available: bool): - with self.__lock.write(): - if self.__closed or available == self.__last_available: - return - self.__last_available = available - - status = DataStoreStatus(available, False) - - if available: - log.warn("Persistent store is available again") - - self.__store_update_sink.update_status(status) - - if available: - with self.__lock.write(): - if self.__poller is not None: - self.__poller.stop() - self.__poller = None - - return - - log.warn("Detected persistent store unavailability; updates will be cached until it recovers") - task = RepeatingTask.at_interval("ldclient.check-availability", 0.5, 0, self.__check_availability) - - with self.__lock.write(): - # Do not start a poller after close() has run. - if self.__closed: - return - self.__poller = task - self.__poller.start() - - def __check_availability(self): - try: - if self.store.is_available(): - self.__update_availability(True) - except BaseException as e: - log.error("Unexpected error from data store status function: %s", e) - - def is_monitoring_enabled(self) -> bool: - """Returns the monitoring setting of the wrapped store.""" - return self.store.is_monitoring_enabled() - - def is_available(self) -> bool: - """Returns the result of the availability check of the wrapped store.""" - return self.store.is_available() - - def close(self) -> None: - """Stops the availability poller and closes the wrapped store. - - Waits for a write in progress. Later writes do nothing. - """ - with self.__write_lock: - with self.__lock.write(): - self.__closed = True - poller_to_stop = self.__poller - self.__poller = None - - if poller_to_stop is not None: - poller_to_stop.stop() - - self.store.close() - - -class _ReadOnlyFeatureStoreView(ReadOnlyStore): - """Read-only view of a feature store. - - Serves every read from the wrapped store. Items that a custom feature store - keeps as raw dicts are decoded into model objects; items that are already - models pass through unchanged. - """ - - def __init__(self, store: FeatureStore): - self._store = store - - def get(self, kind: VersionedDataKind, key: str, callback: Callable[[Any], Any] = lambda x: x) -> Any: - item = self._store.get(kind, key, lambda x: x) - return callback(_decode(kind, item)) - - def all(self, kind: VersionedDataKind, callback: Callable[[Any], Any] = lambda x: x) -> Any: - items = self._store.all(kind, lambda x: x) - return callback({key: _decode(kind, value) for key, value in items.items()}) - - @property - def initialized(self) -> bool: - return self._store.initialized - - -class FDv1(DataSystem): - """ - FDv1 wires the existing v1 data source and store behavior behind the - generic DataSystem surface. - """ - - def __init__(self, config: Config): - self._config = config - - # Set up data store plumbing - self._data_store_listeners = Listeners() - self._data_store_update_sink = DataStoreUpdateSinkImpl( - self._data_store_listeners - ) - self._store_wrapper: FeatureStore = _FeatureStoreClientWrapper( - self._config.feature_store, self._data_store_update_sink - ) - self._store_view = _ReadOnlyFeatureStoreView(self._store_wrapper) - self._data_store_status_provider_impl = DataStoreStatusProviderImpl( - self._store_wrapper, self._data_store_update_sink - ) - - # Set up data source plumbing - self._data_source_listeners = Listeners() - self._flag_change_listeners = Listeners() - self._data_source_update_sink = DataSourceUpdateSinkImpl( - self._store_wrapper, - self._data_source_listeners, - self._flag_change_listeners, - ) - self._data_source_status_provider_impl = DataSourceStatusProviderImpl( - self._data_source_listeners, self._data_source_update_sink - ) - - # Ensure v1 processors can find the sink via config for status updates - self._config._data_source_update_sink = self._data_source_update_sink - - # Update processor created in start(), because it needs the ready Event - self._update_processor: Optional[UpdateProcessor] = None - - # Diagnostic accumulator provided by client for streaming metrics - self._diagnostic_accumulator: Optional[DiagnosticAccumulator] = None - - def start(self, set_on_ready: Event): - """ - Starts the v1 update processor and returns immediately. The provided - Event is set by the processor upon first successful initialization or - upon permanent failure. - """ - update_processor = self._make_update_processor( - self._config, self._store_wrapper, set_on_ready - ) - self._update_processor = update_processor - update_processor.start() - - def stop(self): - if self._update_processor is not None: - self._update_processor.stop() - self._store_wrapper.close() - - @property - def store(self) -> ReadOnlyStore: - return self._store_view - - @property - def environment_id(self) -> Optional[str]: - return self._data_source_update_sink.environment_id - - def set_diagnostic_accumulator(self, diagnostic_accumulator: DiagnosticAccumulator): - """ - Sets the diagnostic accumulator for streaming initialization metrics. - This should be called before start() to ensure metrics are collected. - """ - self._diagnostic_accumulator = diagnostic_accumulator - - @property - def data_source_status_provider(self) -> DataSourceStatusProvider: - return self._data_source_status_provider_impl - - @property - def data_store_status_provider(self) -> DataStoreStatusProvider: - return self._data_store_status_provider_impl - - @property - def flag_change_listeners(self) -> Listeners: - return self._flag_change_listeners - - @property - def data_availability(self) -> DataAvailability: - if self._config.offline: - return DataAvailability.DEFAULTS - - if self._update_processor is not None and self._update_processor.initialized(): - return DataAvailability.REFRESHED - - if self._store_wrapper.initialized: - return DataAvailability.CACHED - - return DataAvailability.DEFAULTS - - @property - def target_availability(self) -> DataAvailability: - if self._config.offline: - return DataAvailability.DEFAULTS - # In LDD mode or normal connected modes, the ideal is to be refreshed - return DataAvailability.REFRESHED - - def _make_update_processor(self, config: Config, store: FeatureStore, ready: Event): - if config.update_processor_class: - return config.update_processor_class(config, store, ready) - - if config.offline or config.use_ldd: - return NullUpdateProcessor(config, store, ready) - - if config.stream: - return StreamingUpdateProcessor(config, store, ready, self._diagnostic_accumulator) - - # Polling mode - feature_requester = ( - config.feature_requester_class(config) - if config.feature_requester_class is not None - else FeatureRequesterImpl(config) - ) - return PollingUpdateProcessor(config, feature_requester, store, ready) diff --git a/ldclient/impl/datasystem/fdv2.py b/ldclient/impl/datasystem/fdv2.py index 0b128c44..ec2b0b92 100644 --- a/ldclient/impl/datasystem/fdv2.py +++ b/ldclient/impl/datasystem/fdv2.py @@ -1,6 +1,6 @@ import time from queue import Queue -from threading import Event, Thread +from threading import Event, Lock, Thread from typing import Any, Callable, Dict, List, Mapping, Optional from ldclient.config import Config, DataSourceBuilder, DataSystemConfig @@ -68,6 +68,10 @@ def __init__(self, store: FeatureStore, store_update_sink: DataStoreStatusProvid self.__store_update_sink = store_update_sink self.__monitoring_enabled = self.is_monitoring_enabled() + # Held for each write and by close(). A write that starts after + # close() does nothing, and close() waits for a write in progress. + self.__write_lock = Lock() + # Covers the following variables self.__lock = ReadWriteLock() self.__last_available = True @@ -75,7 +79,7 @@ def __init__(self, store: FeatureStore, store_update_sink: DataStoreStatusProvid self.__closed = False def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, Dict[Any, Any]]]): - return self.__wrapper(lambda: self.store.init(_FeatureStoreDataSetSorter.sort_all_collections(all_data))) + self.__write(lambda: self.store.init(_FeatureStoreDataSetSorter.sort_all_collections(all_data)), None) def get(self, kind, key, callback): return self.__wrapper(lambda: self.store.get(kind, key, callback)) @@ -84,10 +88,10 @@ def all(self, kind, callback): return self.__wrapper(lambda: self.store.all(kind, callback)) def delete(self, kind, key, version) -> bool: - return self.__wrapper(lambda: self.store.delete(kind, key, version)) + return self.__write(lambda: self.store.delete(kind, key, version), False) def upsert(self, kind, item) -> bool: - return self.__wrapper(lambda: self.store.upsert(kind, item)) + return self.__write(lambda: self.store.upsert(kind, item), False) @property def initialized(self) -> bool: @@ -112,6 +116,19 @@ def __wrapper(self, fn: Callable): self.__update_availability(False) raise + def __write(self, fn: Callable, result_if_closed: Any): + # The failure is reported after the lock is released. A status listener can then + # write or close the client without a deadlock. + try: + with self.__write_lock: + if self.__closed: + return result_if_closed + return fn() + except BaseException: + if self.__monitoring_enabled: + self.__update_availability(False) + raise + def __update_availability(self, available: bool): state_changed = False poller_to_stop = None @@ -165,15 +182,17 @@ def is_available(self) -> bool: def close(self): """ Closes the wrapper. Stops the availability poller if it runs, then closes the wrapped store. + Waits for a write in progress. Later writes do nothing. """ poller_to_stop = None - with self.__lock.write(): - if self.__closed: - return - self.__closed = True - poller_to_stop = self.__poller - self.__poller = None + with self.__write_lock: + with self.__lock.write(): + if self.__closed: + return + self.__closed = True + poller_to_stop = self.__poller + self.__poller = None if poller_to_stop is not None: poller_to_stop.stop() @@ -207,9 +226,6 @@ def __init__( self._config = config self._data_system_config = data_system_config - if config.payload_filter_key is not None: - log.warning("Payload filtering is not supported with the FDv2 data system; the configured payload filter has no effect on FDv2 requests") - self._synchronizers: List[DataSourceBuilder[Synchronizer]] = list(data_system_config.synchronizers) if data_system_config.synchronizers else [] self._fdv1_fallback_synchronizer_builder = data_system_config.fdv1_fallback_synchronizer self._disabled = config.offline diff --git a/ldclient/impl/events/diagnostics.py b/ldclient/impl/events/diagnostics.py index 9a799c75..914f028c 100644 --- a/ldclient/impl/events/diagnostics.py +++ b/ldclient/impl/events/diagnostics.py @@ -64,14 +64,12 @@ def _create_diagnostic_config_object(config): 'socketTimeoutMillis': config.http.read_timeout * 1000, 'eventsFlushIntervalMillis': config.flush_interval * 1000, 'usingProxy': config.http.http_proxy is not None, - 'streamingDisabled': not config.stream, - 'usingRelayDaemon': config.use_ldd, 'allAttributesPrivate': config.all_attributes_private, 'pollingIntervalMillis': config.poll_interval * 1000, 'userKeysCapacity': config.context_keys_capacity, 'userKeysFlushIntervalMillis': config.context_keys_flush_interval * 1000, 'diagnosticRecordingIntervalMillis': config.diagnostic_recording_interval * 1000, - 'dataStoreType': _get_component_type_name(config.feature_store, config, 'memory'), + 'dataStoreType': _get_component_type_name(_persistent_store(config), config, 'memory'), } @@ -90,6 +88,11 @@ def _create_diagnostic_platform_object(): } +def _persistent_store(config): + datasystem_config = config.datasystem_config + return datasystem_config.data_store if datasystem_config is not None else None + + def _get_component_type_name(component, config, default_name): if component is not None: if callable(getattr(component, 'describe_configuration', None)): diff --git a/ldclient/impl/integrations/files/file_data_source.py b/ldclient/impl/integrations/files/file_data_source.py deleted file mode 100644 index 7d5e0d31..00000000 --- a/ldclient/impl/integrations/files/file_data_source.py +++ /dev/null @@ -1,190 +0,0 @@ -import json -import os -import time -import traceback -from typing import Optional - -from ldclient.impl.datasource.datasource_common import require_update_sink -from ldclient.impl.repeating_task import RepeatingTask -from ldclient.impl.util import log -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceUpdateSink, - UpdateProcessor -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -have_yaml = False -try: - import yaml - - have_yaml = True -except ImportError: - pass - -have_watchdog = False -try: - import watchdog - import watchdog.events - import watchdog.observers - - have_watchdog = True -except ImportError: - pass - - -def _sanitize_json_item(item): - if not ('version' in item): - item['version'] = 1 - - -class _FileDataSource(UpdateProcessor): - def __init__(self, store, data_source_update_sink: Optional[DataSourceUpdateSink], ready, paths, auto_update, poll_interval, force_polling): - self._data_source_update_sink: DataSourceUpdateSink = require_update_sink(data_source_update_sink) - self._ready = ready - self._inited = False - self._paths = paths - if isinstance(self._paths, str): - self._paths = [self._paths] - self._auto_update = auto_update - self._auto_updater = None - self._poll_interval = poll_interval - self._force_polling = force_polling - - def start(self): - self._load_all() - - if self._auto_update: - self._auto_updater = self._start_auto_updater() - - # We will signal readiness immediately regardless of whether the file load succeeded or failed - - # the difference can be detected by checking initialized() - self._ready.set() - - def stop(self): - if self._auto_updater: - self._auto_updater.stop() - - def initialized(self): - return self._inited - - def _load_all(self): - all_data = {FEATURES: {}, SEGMENTS: {}} - for path in self._paths: - try: - self._load_file(path, all_data) - except Exception as e: - log.error('Unable to load flag data from "%s": %s' % (path, repr(e))) - traceback.print_exc() - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, DataSourceErrorInfo(DataSourceErrorKind.INVALID_DATA, 0, time.time, str(e))) - return - try: - self._data_source_update_sink.init(all_data) - self._inited = True - self._data_source_update_sink.update_status(DataSourceState.VALID, None) - except Exception as e: - log.error('Unable to store data: %s' % repr(e)) - traceback.print_exc() - self._data_source_update_sink.update_status(DataSourceState.INTERRUPTED, DataSourceErrorInfo(DataSourceErrorKind.UNKNOWN, 0, time.time, str(e))) - - def _load_file(self, path, all_data): - content = None - with open(path, 'r') as f: - content = f.read() - parsed = self._parse_content(content) - for key, flag in parsed.get('flags', {}).items(): - _sanitize_json_item(flag) - self._add_item(all_data, FEATURES, flag) - for key, value in parsed.get('flagValues', {}).items(): - self._add_item(all_data, FEATURES, self._make_flag_with_value(key, value)) - for key, segment in parsed.get('segments', {}).items(): - _sanitize_json_item(segment) - self._add_item(all_data, SEGMENTS, segment) - - def _parse_content(self, content): - if have_yaml: - return yaml.safe_load(content) # pyyaml correctly parses JSON too - return json.loads(content) - - def _add_item(self, all_data, kind, item): - items = all_data[kind] - key = item.get('key') - if items.get(key) is None: - items[key] = item - else: - raise Exception('In %s, key "%s" was used more than once' % (kind.namespace, key)) - - def _make_flag_with_value(self, key, value): - return {'key': key, 'version': 1, 'on': True, 'fallthrough': {'variation': 0}, 'variations': [value]} - - def _start_auto_updater(self): - resolved_paths = [] - for path in self._paths: - try: - resolved_paths.append(os.path.realpath(path)) - except Exception: - log.warning('Cannot watch for changes to data file "%s" because it is an invalid path' % path) - if have_watchdog and not self._force_polling: - return _FileDataSource.WatchdogAutoUpdater(resolved_paths, self._load_all) - else: - return _FileDataSource.PollingAutoUpdater(resolved_paths, self._load_all, self._poll_interval) - - # Watch for changes to data files using the watchdog package. This uses native OS filesystem notifications - # if available for the current platform. - class WatchdogAutoUpdater: - def __init__(self, resolved_paths, reloader): - watched_files = set(resolved_paths) - - class LDWatchdogHandler(watchdog.events.FileSystemEventHandler): - def on_any_event(self, event): - if event.src_path in watched_files: - reloader() - - dir_paths = set() - for path in resolved_paths: - dir_paths.add(os.path.dirname(path)) - - self._observer = watchdog.observers.Observer() - handler = LDWatchdogHandler() - for path in dir_paths: - self._observer.schedule(handler, path) - self._observer.start() - - def stop(self): - self._observer.stop() - self._observer.join() - - # Watch for changes to data files by polling their modification times. This is used if auto-update is - # on but the watchdog package is not installed. - class PollingAutoUpdater: - def __init__(self, resolved_paths, reloader, interval): - self._paths = resolved_paths - self._reloader = reloader - self._file_times = self._check_file_times() - self._timer = RepeatingTask.at_interval("ldclient.datasource.file.poll", interval, interval, self._poll) - self._timer.start() - - def stop(self): - self._timer.stop() - - def _poll(self): - new_times = self._check_file_times() - changed = False - for file_path, file_time in self._file_times.items(): - if new_times.get(file_path) is not None and new_times.get(file_path) != file_time: - changed = True - break - self._file_times = new_times - if changed: - self._reloader() - - def _check_file_times(self): - ret = {} - for path in self._paths: - try: - ret[path] = os.path.getmtime(path) - except Exception: - ret[path] = None - return ret diff --git a/ldclient/impl/integrations/test_data/__init__.py b/ldclient/impl/integrations/test_data/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/ldclient/impl/integrations/test_data/test_data_source.py b/ldclient/impl/integrations/test_data/test_data_source.py deleted file mode 100644 index cb3720cd..00000000 --- a/ldclient/impl/integrations/test_data/test_data_source.py +++ /dev/null @@ -1,28 +0,0 @@ -from ldclient.interfaces import UpdateProcessor -from ldclient.versioned_data_kind import FEATURES - -# This is the internal component that's created when you initialize an SDK instance that is using -# TestData. The TestData object manages the setup of the fake data, and it broadcasts the data -# through _TestDataSource to inject it into the SDK. If there are multiple SDK instances connected -# to a TestData, each has its own _TestDataSource. - - -class _TestDataSource(UpdateProcessor): - - def __init__(self, feature_store, test_data, ready): - self._feature_store = feature_store - self._test_data = test_data - self._ready = ready - - def start(self): - self._ready.set() - self._feature_store.init(self._test_data._make_init_data()) - - def stop(self): - self._test_data._closed_instance(self) - - def initialized(self): - return True - - def upsert(self, new_flag): - self._feature_store.upsert(FEATURES, new_flag) diff --git a/ldclient/impl/retry.py b/ldclient/impl/retry.py deleted file mode 100644 index edfd1b85..00000000 --- a/ldclient/impl/retry.py +++ /dev/null @@ -1,305 +0,0 @@ -""" -Computes how long to wait before a failed operation is tried again. - -Each failure falls into one of two classes. A ``NORMAL`` failure is one the -service is expected to recover from soon, so the wait stays short. An -``UNEXPECTED`` failure points to a problem that a person has to fix, such as a -rejected SDK key, so the wait becomes much longer. Only an HTTP status can be -``UNEXPECTED``; every network and TLS failure is ``NORMAL``. Neither class ever -tells the caller to give up. There is always a next attempt. - -The wait doubles after each failure, up to a ceiling. A random jitter is then -subtracted, so that many callers do not all try again at the same moment. The -wait never falls below the caller's operating cadence. - -:class:`RetryState` holds the state for one caller. Use :func:`for_streaming` -or :func:`for_polling` to build one with the right parameters and reset policy. -""" - -# currently excluded from documentation - see docs/README.md - -import math -import random -import time -from enum import Enum -from typing import Optional, Protocol - -from ldclient.config import ( - DEFAULT_INITIAL_RECONNECT_DELAY, - DEFAULT_POLL_INTERVAL -) -from ldclient.impl.util import log - -# The delay ceiling of the normal regime for streaming, in seconds. -NORMAL_STREAMING_CEILING_DELAY = 30 - -# The delay bounds of the extended regime, in seconds. A component enters the -# extended regime after an unexpected failure. -EXTENDED_INITIAL_DELAY = 5 * 60 -EXTENDED_CEILING_DELAY = 60 * 60 - -# How long streaming must operate without a failure before its retry state -# resets, in seconds. -STREAMING_RESET_INTERVAL = 60 - -# How many polls in a row must succeed before polling's retry state resets. -POLLING_RESET_SUCCESSES = 2 - -# HTTP statuses in the 4xx range that are still normal failures. Every other -# 4xx is unexpected. -_NORMAL_4XX_STATUSES = frozenset([400, 408, 429]) - -# An upper bound on the backoff exponent, so a long outage cannot overflow the -# delay computation. Any real ceiling is reached long before this. -_MAX_BACKOFF_EXPONENT = 30 - - -def _usable_delay(value: float, default: float, name: str) -> float: - """ - Returns the delay to use. A value that is not a positive, finite number of - seconds is replaced by the default. - - :param value: the configured number of seconds - :param default: the value to use when ``value`` is not usable - :param name: the option name, for the warning message - """ - - if value > 0 and math.isfinite(value): - return value - log.warning("%s must be a positive, finite number of seconds; using the default of %ss" % (name, default)) - return default - - -class FailureKind(Enum): - """How a failure is classified, which decides how long the next wait is.""" - - NORMAL = 'normal' - """A failure the service is expected to recover from without help.""" - - UNEXPECTED = 'unexpected' - """A failure that suggests a problem a person has to fix. The component - keeps retrying, but much less often.""" - - -def classify_http_status(status: int) -> FailureKind: - """ - Classifies an HTTP status. - - ``400``, ``408`` and ``429`` are normal, as is any ``5xx``. Every other - ``4xx`` -- including ``401`` and ``403`` -- is unexpected. - """ - if 400 <= status < 500 and status not in _NORMAL_4XX_STATUSES: - return FailureKind.UNEXPECTED - return FailureKind.NORMAL - - -class ResetPolicy(Protocol): - """Decides when a component has operated well enough for long enough that - its retry state should reset. This is the only behavioral difference - between streaming and polling.""" - - def note_healthy(self) -> None: - """Records that the component is operating normally.""" - ... - - def note_failure(self) -> None: - """Records a failure, which ends any healthy stretch in progress.""" - ... - - def is_satisfied(self) -> bool: - """Reports whether the reset condition is met.""" - ... - - -class AfterHealthyFor(ResetPolicy): - """Resets once the component has operated without failing for - ``seconds``. This is the streaming policy.""" - - def __init__(self, seconds: float): - self._healthy_seconds = seconds - self._healthy_since: Optional[float] = None - - def note_healthy(self) -> None: - """Records the monotonic time the component became healthy. Calling - this again while it is still healthy does not move that time.""" - if self._healthy_since is None: - self._healthy_since = time.monotonic() - - def note_failure(self) -> None: - self._healthy_since = None - - def is_satisfied(self) -> bool: - if self._healthy_since is None: - return False - return time.monotonic() - self._healthy_since >= self._healthy_seconds - - -class AfterConsecutiveSuccesses(ResetPolicy): - """Resets once ``count`` operations in a row have succeeded. This is the - polling policy.""" - - def __init__(self, count: int): - self._count = count - self._successes = 0 - - def note_healthy(self) -> None: - self._successes += 1 - - def note_failure(self) -> None: - self._successes = 0 - - def is_satisfied(self) -> bool: - return self._successes >= self._count - - -class RetryState: - """ - Tracks how long a data source should wait before its next attempt. - - A failure moves the state on and decides the next wait, which - :attr:`next_delay` reports. The delay is - ``min(min_delay * 2 ** (attempts - 1), max_delay)``, less a random jitter - of up to half of it, and never less than the operating cadence. - - An unexpected failure moves the state to the extended regime, which raises - both delay bounds. The bounds stay raised until the reset condition is met, - so a normal failure that follows cannot lower them. - """ - - def __init__( - self, - normal_initial_delay: float, - normal_ceiling_delay: float, - extended_initial_delay: float, - extended_ceiling_delay: float, - reset_policy: ResetPolicy, - operating_cadence: float = 0, - ): - """ - :param normal_initial_delay: the delay before the first retry in the - normal regime, in seconds - :param normal_ceiling_delay: the longest normal-regime delay, in - seconds - :param extended_initial_delay: the delay before the first retry in the - extended regime, in seconds - :param extended_ceiling_delay: the longest extended-regime delay, in - seconds - :param reset_policy: decides when the retry state resets - :param operating_cadence: the wait between healthy operations, in - seconds; no wait is ever shorter than this. Zero for a component - that operates continuously. - """ - self._normal_initial_delay = normal_initial_delay - self._normal_ceiling_delay = normal_ceiling_delay - self._extended_initial_delay = extended_initial_delay - self._extended_ceiling_delay = extended_ceiling_delay - self._reset_policy = reset_policy - self._operating_cadence = operating_cadence - - self._attempts = 0 - self._extended = False - self._min_delay = self._normal_initial_delay - self._max_delay = max(self._normal_ceiling_delay, self._normal_initial_delay) - # Read before any outcome is recorded, this is the ordinary interval. - self._next_delay = self._operating_cadence - - @property - def next_delay(self) -> float: - """The wait before the next operation, in seconds, as the last recorded - outcome decided it.""" - return self._next_delay - - def record_failure(self, kind: FailureKind) -> None: - """ - Records a failed attempt, and decides the wait before the next one. - - The state moves on before the wait is computed, so :attr:`next_delay` - always reflects the failure just recorded. - - :param kind: how the failure was classified - """ - # Only a time-based policy needs this: nothing runs while a stream is healthy. - self._reset_if_due() - self._reset_policy.note_failure() - - if kind is FailureKind.UNEXPECTED and not self._extended: - # Moving to the extended regime raises both bounds and starts the - # delay sequence over. Only the move does this: a later unexpected - # failure keeps counting up, so the delay is not pinned to the - # extended initial delay. - self._extended = True - self._min_delay = self._extended_initial_delay - self._max_delay = max(self._extended_ceiling_delay, self._min_delay) - self._attempts = 1 - else: - self._attempts += 1 - - exponent = min(max(self._attempts - 1, 0), _MAX_BACKOFF_EXPONENT) - delay = min(self._min_delay * (2**exponent), self._max_delay) - jitter = random.random() * delay / 2 - - self._next_delay = max(delay - jitter, self._operating_cadence) - - def record_success(self) -> None: - """ - Records a successful operation, and resets the retry state if that is - now enough. - - The wait before the next operation goes back to the ordinary interval, - even when the retry state is still raised, because a backoff wait - applies to a retry and not to every operation. - """ - self._reset_policy.note_healthy() - self._reset_if_due() - self._next_delay = self._operating_cadence - - def _reset_if_due(self) -> None: - """Clears the retry state when the reset policy is satisfied, returning - the delay bounds to the normal regime.""" - if not self._reset_policy.is_satisfied(): - return - self._attempts = 0 - self._extended = False - self._min_delay = self._normal_initial_delay - self._max_delay = max(self._normal_ceiling_delay, self._normal_initial_delay) - - -def for_streaming(initial_reconnect_delay: float) -> RetryState: - """ - Builds the retry state for a streaming data source. - - Streaming's cadence is zero, so a healthy stream never waits. An invalid - delay value is replaced by the documented default; one longer than a - ceiling raises that bound rather than being cut down to it. - """ - initial_reconnect_delay = _usable_delay( - initial_reconnect_delay, DEFAULT_INITIAL_RECONNECT_DELAY, 'initial_reconnect_delay' - ) - return RetryState( - normal_initial_delay=initial_reconnect_delay, - normal_ceiling_delay=NORMAL_STREAMING_CEILING_DELAY, - extended_initial_delay=max(EXTENDED_INITIAL_DELAY, initial_reconnect_delay), - extended_ceiling_delay=EXTENDED_CEILING_DELAY, - reset_policy=AfterHealthyFor(STREAMING_RESET_INTERVAL), - operating_cadence=0 - ) - - -def for_polling(poll_interval: float) -> RetryState: - """ - Builds the retry state for a polling data source. - - The poll interval is polling's cadence and its normal ceiling, so a normal - failure waits the interval rather than backing off past it. An invalid - interval is replaced by the documented default. No wait is ever shorter - than the interval, so the cadence wins over the extended ceiling. - """ - poll_interval = _usable_delay(poll_interval, DEFAULT_POLL_INTERVAL, 'poll_interval') - return RetryState( - normal_initial_delay=poll_interval, - normal_ceiling_delay=poll_interval, - extended_initial_delay=max(EXTENDED_INITIAL_DELAY, poll_interval), - extended_ceiling_delay=EXTENDED_CEILING_DELAY, - reset_policy=AfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES), - operating_cadence=poll_interval, - ) diff --git a/ldclient/impl/stubs.py b/ldclient/impl/stubs.py index 58b7193f..c1c2bbfc 100644 --- a/ldclient/impl/stubs.py +++ b/ldclient/impl/stubs.py @@ -1,9 +1,4 @@ -from ldclient.interfaces import ( - AsyncEventProcessor, - AsyncUpdateProcessor, - EventProcessor, - UpdateProcessor -) +from ldclient.interfaces import AsyncEventProcessor, EventProcessor class NullEventProcessor(EventProcessor): @@ -23,20 +18,6 @@ def flush(self): pass -class NullUpdateProcessor(UpdateProcessor): - def __init__(self, config, store, ready): - self._ready = ready - - def start(self): - self._ready.set() - - def stop(self): - pass - - def initialized(self): - return True - - class AsyncNullEventProcessor(AsyncEventProcessor): """Async no-op event processor. The async equivalent of :class:`NullEventProcessor`, so the async client can await ``stop()`` @@ -56,21 +37,3 @@ def flush(self): async def flush_and_wait(self, timeout: float) -> bool: return True - - -class AsyncNullUpdateProcessor(AsyncUpdateProcessor): - """Async no-op update processor. The async equivalent of - :class:`NullUpdateProcessor`, used by async FDv1 when offline or in LDD - mode so the data system can await ``stop()`` uniformly.""" - - def __init__(self, config, store, ready): - self._ready = ready - - def start(self): - self._ready.set() - - async def stop(self): - pass - - def initialized(self): - return True diff --git a/ldclient/impl/util.py b/ldclient/impl/util.py index deec78c8..d2f076e8 100644 --- a/ldclient/impl/util.py +++ b/ldclient/impl/util.py @@ -115,17 +115,6 @@ def check_uwsgi(): ) -class Event: - def __init__(self, data='', event='message', event_id=None, retry=None): - self.data = data - self.event = event - self.id = event_id - self.retry = retry - - def __str__(self, *args, **kwargs): - return self.data - - class UnsuccessfulResponseException(Exception): def __init__(self, status): super(UnsuccessfulResponseException, self).__init__("HTTP error %d" % status) @@ -136,15 +125,7 @@ def status(self): return self._status -def throw_if_unsuccessful_response(resp): - if resp.status >= 400: - raise UnsuccessfulResponseException(resp.status) - - def is_http_error_recoverable(status): - """ - Deprecated. Use :func:`ldclient.impl.retry.classify_http_status` instead. - """ if status >= 400 and status < 500: return status in _RETRYABLE_STATUSES # all other 4xx besides these are unrecoverable return True # all other errors are recoverable @@ -155,10 +136,6 @@ def http_error_description(status): def http_error_message(status, context, retryable_message="will retry"): - """ - Deprecated. The FDv1 data sources build their own message, so that it can - report the real retry delay. - """ return "Received %s for %s - %s" % (http_error_description(status), context, retryable_message if is_http_error_recoverable(status) else "giving up permanently") diff --git a/ldclient/integrations/__init__.py b/ldclient/integrations/__init__.py index 5d49e5cb..71ee0f93 100644 --- a/ldclient/integrations/__init__.py +++ b/ldclient/integrations/__init__.py @@ -3,8 +3,7 @@ other than LaunchDarkly. """ -from threading import Event -from typing import Any, Callable, Dict, List, Mapping, Optional +from typing import Any, Dict, List, Mapping, Optional from ldclient import log from ldclient.config import Config, DataSourceBuilder @@ -19,7 +18,6 @@ from ldclient.impl.integrations.dynamodb.dynamodb_feature_store import ( _DynamoDBFeatureStoreCore ) -from ldclient.impl.integrations.files.file_data_source import _FileDataSource from ldclient.impl.integrations.files.file_data_sourcev2 import ( FileDataSourceV2Builder ) @@ -29,7 +27,7 @@ from ldclient.impl.integrations.redis.redis_feature_store import ( _RedisFeatureStoreCore ) -from ldclient.interfaces import BigSegmentStore, FeatureStore, UpdateProcessor +from ldclient.interfaces import BigSegmentStore class Consul: @@ -46,14 +44,17 @@ def new_feature_store( For more details about how and why you can use a persistent feature store, see the `SDK reference guide `_. - To use this method, you must first install the ``python-consul`` package. Then, put the object - returned by this method into the ``feature_store`` property of your client configuration - (:class:`ldclient.config.Config`). + To use this method, you must first install the ``python-consul`` package. Then, pass the object + returned by this method to :func:`ldclient.datasystem.persistent_store`, or to + :func:`ldclient.datasystem.daemon` if another process keeps the store up to date, and set the + result as the ``datasystem_config`` of your client configuration (:class:`ldclient.config.Config`). :: + from ldclient import datasystem + from ldclient.config import Config from ldclient.integrations import Consul store = Consul.new_feature_store() - config = Config(feature_store=store) + config = Config('sdk-key', datasystem_config=datasystem.persistent_store(store).build()) :param host: hostname of the Consul server (uses ``localhost`` if omitted) :param port: port of the Consul server (uses 8500 if omitted) @@ -82,13 +83,17 @@ def new_feature_store(table_name: str, prefix: Optional[str] = None, dynamodb_op `SDK reference guide `_. To use this method, you must first install the ``boto3`` package for the AWS SDK. - Then, put the object returned by this method into the ``feature_store`` property of your - client configuration (:class:`ldclient.config.Config`). + Then, pass the object + returned by this method to :func:`ldclient.datasystem.persistent_store`, or to + :func:`ldclient.datasystem.daemon` if another process keeps the store up to date, and set the + result as the ``datasystem_config`` of your client configuration (:class:`ldclient.config.Config`). :: + from ldclient import datasystem + from ldclient.config import Config from ldclient.integrations import DynamoDB store = DynamoDB.new_feature_store("my-table-name") - config = Config(feature_store=store) + config = Config('sdk-key', datasystem_config=datasystem.persistent_store(store).build()) Note that the DynamoDB table must already exist; the LaunchDarkly SDK does not create the table automatically, because it has no way of knowing what additional properties (such as permissions @@ -160,15 +165,18 @@ def async_feature_store(table_name: str, prefix: Optional[str] = None, dynamodb_ For more details about how and why you can use a persistent feature store, see the `SDK reference guide `_. - To use this method, you must first install the ``aioboto3`` package. Then, put the object - returned by this method into the ``feature_store`` property of your client configuration - when constructing an ``AsyncLDClient``. + To use this method, you must first install the ``aioboto3`` package. Then, pass the object + returned by this method to :func:`ldclient.async_datasystem.persistent_store`, or to + :func:`ldclient.async_datasystem.daemon` if another process keeps the store up to date, and set + the result as the ``datasystem_config`` of your client configuration + (:class:`ldclient.async_config.AsyncConfig`). :: - from ldclient.config import Config + from ldclient import async_datasystem + from ldclient.async_config import AsyncConfig from ldclient.integrations import DynamoDB store = DynamoDB.async_feature_store("my-table-name") - config = Config(feature_store=store) + config = AsyncConfig('sdk-key', datasystem_config=async_datasystem.persistent_store(store).build()) The data layout matches :func:`new_feature_store`, so an async and a synchronous SDK can share one DynamoDB table. @@ -218,15 +226,17 @@ def new_feature_store( For more details about how and why you can use a persistent feature store, see the `SDK reference guide `_. - To use this method, you must first install the ``redis`` package. Then, put the object - returned by this method into the ``feature_store`` property of your client configuration - (:class:`ldclient.config.Config`). + To use this method, you must first install the ``redis`` package. Then, pass the object + returned by this method to :func:`ldclient.datasystem.persistent_store`, or to + :func:`ldclient.datasystem.daemon` if another process keeps the store up to date, and set the + result as the ``datasystem_config`` of your client configuration (:class:`ldclient.config.Config`). :: + from ldclient import datasystem from ldclient.config import Config from ldclient.integrations import Redis store = Redis.new_feature_store() - config = Config(feature_store=store) + config = Config('sdk-key', datasystem_config=datasystem.persistent_store(store).build()) :param url: the URL of the Redis host; defaults to ``DEFAULT_URL`` :param prefix: a namespace prefix to be prepended to all Redis keys; defaults to @@ -305,15 +315,18 @@ def async_feature_store(url: str = 'redis://localhost:6379/0', prefix: Optional[ For more details about how and why you can use a persistent feature store, see the `SDK reference guide `_. - To use this method, you must first install the ``redis`` package (version >=5.0.1). Then, put - the object returned by this method into the ``feature_store`` property of your client - configuration when constructing an ``AsyncLDClient``. + To use this method, you must first install the ``redis`` package (version >=5.0.1). Then, pass + the object returned by this method to :func:`ldclient.async_datasystem.persistent_store`, or to + :func:`ldclient.async_datasystem.daemon` if another process keeps the store up to date, and set + the result as the ``datasystem_config`` of your client configuration + (:class:`ldclient.async_config.AsyncConfig`). :: - from ldclient.config import Config + from ldclient import async_datasystem + from ldclient.async_config import AsyncConfig from ldclient.integrations import Redis store = Redis.async_feature_store() - config = Config(feature_store=store) + config = AsyncConfig('sdk-key', datasystem_config=async_datasystem.persistent_store(store).build()) The data layout matches :func:`new_feature_store`, so an async and a synchronous SDK can share one Redis instance. @@ -375,50 +388,6 @@ def async_big_segment_store(url: str = 'redis://localhost:6379/0', prefix: Optio class Files: """Provides factory methods for integrations with filesystem data.""" - @staticmethod - def new_data_source(paths: List[str], auto_update: bool = False, poll_interval: float = 1, force_polling: bool = False) -> Optional[Callable[[Config, FeatureStore, Event], UpdateProcessor]]: - """Provides a way to use local files as a source of feature flag state. This would typically be - used in a test environment, to operate using a predetermined feature flag state without an - actual LaunchDarkly connection. - - To use this component, call ``new_data_source``, specifying the file path(s) of your data file(s) - in the ``paths`` parameter; then put the value returned by this method into the ``update_processor_class`` - property of your LaunchDarkly client configuration (:class:`ldclient.config.Config`). - :: - - from ldclient.integrations import Files - data_source = Files.new_data_source(paths=[ myFilePath ]) - config = Config(update_processor_class=data_source) - - This will cause the client not to connect to LaunchDarkly to get feature flags. The - client may still make network connections to send analytics events, unless you have disabled - this in your configuration with ``send_events`` or ``offline``. - - The format of the data files is described in the SDK Reference Guide on - `Reading flags from a file `_. - Note that in order to use YAML, you will need to install the ``pyyaml`` package. - - If the data source encounters any error in any file-- malformed content, a missing file, or a - duplicate key-- it will not load flags from any of the files. - - :param paths: the paths of the source files for loading flag data. These may be absolute paths - or relative to the current working directory. Files will be parsed as JSON unless the ``pyyaml`` - package is installed, in which case YAML is also allowed. - :param auto_update: (default: false) True if the data source should watch for changes to the source file(s) - and reload flags whenever there is a change. The default implementation of this feature is based on - polling the filesystem, which may not perform well; if you install the ``watchdog`` package, its - native file watching mechanism will be used instead. Note that auto-updating will only work if all - of the files you specified have valid directory paths at startup time. - :param poll_interval: (default: 1) the minimum interval, in seconds, between checks for file - modifications-- used only if ``auto_update`` is true, and if the native file-watching mechanism from - ``watchdog`` is not being used. - :param force_polling: (default: false) True if the data source should implement auto-update via - polling the filesystem even if a native mechanism is available. This is mainly for SDK testing. - - :return: an object (actually a lambda) to be stored in the ``update_processor_class`` configuration property - """ - return lambda config, store, ready: _FileDataSource(store, config.data_source_update_sink, ready, paths, auto_update, poll_interval, force_polling) - @staticmethod def new_data_source_v2(paths: str | List[str], poll_interval: float = 1, force_polling: bool = False) -> DataSourceBuilder: """Provides a way to use local files as a source of feature flag state using the FDv2 protocol. @@ -432,28 +401,28 @@ def new_data_source_v2(paths: str | List[str], poll_interval: float = 1, force_p :: from ldclient.integrations import Files - from ldclient.impl.datasystem.config import custom + from ldclient.datasystem import custom file_source = Files.new_data_source_v2(paths=['my_flags.json']) # Use as initializer only data_system = custom().initializers([file_source]).build() - config = Config(data_system=data_system) + config = Config('sdk-key', datasystem_config=data_system) # Use as synchronizer only data_system = custom().synchronizers(file_source).build() - config = Config(data_system=data_system) + config = Config('sdk-key', datasystem_config=data_system) # Use as both initializer and synchronizer data_system = custom().initializers([file_source]).synchronizers(file_source).build() - config = Config(data_system=data_system) + config = Config('sdk-key', datasystem_config=data_system) This will cause the client not to connect to LaunchDarkly to get feature flags. The client may still make network connections to send analytics events, unless you have disabled this in your configuration with ``send_events`` or ``offline``. - The format of the data files is the same as for the v1 file data source, described in the - SDK Reference Guide on `Reading flags from a file `_. + The format of the data files is described in the SDK Reference Guide on + `Reading flags from a file `_. Note that in order to use YAML, you will need to install the ``pyyaml`` package. If the data source encounters any error in any file-- malformed content, a missing file, or a diff --git a/ldclient/integrations/test_data.py b/ldclient/integrations/test_data.py deleted file mode 100644 index 591b2f2b..00000000 --- a/ldclient/integrations/test_data.py +++ /dev/null @@ -1,626 +0,0 @@ -import copy -from typing import Any, Dict, List, Optional, Set, Union - -from ldclient.context import Context -from ldclient.impl.integrations.test_data.test_data_source import ( - _TestDataSource -) -from ldclient.impl.rwlock import ReadWriteLock -from ldclient.versioned_data_kind import FEATURES - -TRUE_VARIATION_INDEX = 0 -FALSE_VARIATION_INDEX = 1 - - -def _variation_for_boolean(variation): - if variation: - return TRUE_VARIATION_INDEX - else: - return FALSE_VARIATION_INDEX - - -class TestData: - """A mechanism for providing dynamically updatable feature flag state in a - simplified form to an SDK client in test scenarios. - - Unlike ``Files``, this mechanism does not use any external resources. It provides only - the data that the application has put into it using the ``update`` method. - :: - - td = TestData.data_source() - td.update(td.flag('flag-key-1').variation_for_all(True)) - - client = LDClient(config=Config('SDK_KEY', update_processor_class = td)) - - # flags can be updated at any time: - td.update(td.flag('flag-key-1'). \\ - variation_for_user('some-user-key', True). \\ - fallthrough_variation(False)) - - The above example uses a simple boolean flag, but more complex configurations are possible using - the methods of the ``FlagBuilder`` that is returned by ``flag``. ``FlagBuilder`` - supports many of the ways a flag can be configured on the LaunchDarkly dashboard, but does not - currently support 1. rule operators other than "in" and "not in", or 2. percentage rollouts. - - If the same ``TestData`` instance is used to configure multiple ``LDClient`` instances, - any changes made to the data will propagate to all of the ``LDClient`` instances. - """ - - # Prevent pytest from treating this as a test class - __test__ = False - - def __init__(self): - self._flag_builders = {} - self._current_flags = {} - self._lock = ReadWriteLock() - self._instances = [] - - def __call__(self, config, store, ready): - data_source = _TestDataSource(store, self, ready) - with self._lock.write(): - self._instances.append(data_source) - - return data_source - - @staticmethod - def data_source() -> 'TestData': - """Creates a new instance of the test data source. - - :return: a new configurable test data source - """ - return TestData() - - def flag(self, key: str) -> 'FlagBuilder': - """Creates or copies a ``FlagBuilder`` for building a test flag configuration. - - If this flag key has already been defined in this ``TestData`` instance, then the builder - starts with the same configuration that was last provided for this flag. - - Otherwise, it starts with a new default configuration in which the flag has ``True`` and - ``False`` variations, is ``True`` for all users when targeting is turned on and - ``False`` otherwise, and currently has targeting turned on. You can change any of those - properties, and provide more complex behavior, using the ``FlagBuilder`` methods. - - Once you have set the desired configuration, pass the builder to ``update``. - - :param str key: the flag key - :return: the flag configuration builder object - """ - with self._lock.read(): - if key in self._flag_builders and self._flag_builders[key]: - return self._flag_builders[key]._copy() - else: - return FlagBuilder(key).boolean_flag() - - def update(self, flag_builder: 'FlagBuilder') -> 'TestData': - """Updates the test data with the specified flag configuration. - - This has the same effect as if a flag were added or modified on the LaunchDarkly dashboard. - It immediately propagates the flag change to any ``LDClient`` instance(s) that you have - already configured to use this ``TestData``. If no ``LDClient`` has been started yet, - it simply adds this flag to the test data which will be provided to any ``LDClient`` that - you subsequently configure. - - Any subsequent changes to this ``FlagBuilder`` instance do not affect the test data, - unless you call ``update`` again. - - :param flag_builder: a flag configuration builder - :return: self (the TestData object) - """ - with self._lock.write(): - old_version = 0 - if flag_builder._key in self._current_flags: - old_flag = self._current_flags[flag_builder._key] - if old_flag: - old_version = old_flag['version'] - - new_flag = flag_builder._build(old_version + 1) - - self._current_flags[flag_builder._key] = new_flag - self._flag_builders[flag_builder._key] = flag_builder._copy() - - for instance in self._instances: - instance.upsert(new_flag) - - return self - - def _make_init_data(self) -> dict: - return {FEATURES: copy.copy(self._current_flags)} - - def _closed_instance(self, instance): - with self._lock.write(): - self._instances.remove(instance) - - -class FlagBuilder: - """A builder for feature flag configurations to be used with :class:`ldclient.integrations.test_data.TestData`. - - :see: :meth:`ldclient.integrations.test_data.TestData.flag()` - :see: :meth:`ldclient.integrations.test_data.TestData.update()` - """ - - def __init__(self, key: str): - """:param str key: The name of the flag""" - self._key = key - self._on = True - self._variations = [] # type: List[Any] - self._off_variation = None # type: Optional[int] - self._fallthrough_variation = None # type: Optional[int] - self._targets = {} # type: Dict[str, Dict[int, Set[str]]] - self._rules = [] # type: List[FlagRuleBuilder] - - # Note that _copy is private by convention, because we don't want developers to - # consider it part of the public API, but it is still called from TestData. - def _copy(self) -> 'FlagBuilder': - """Creates a deep copy of the flag builder. Subsequent updates to the - original ``FlagBuilder`` object will not update the copy and vice versa. - - :return: a copy of the flag builder object - """ - to = FlagBuilder(self._key) - - to._on = self._on - to._variations = copy.copy(self._variations) - to._off_variation = self._off_variation - to._fallthrough_variation = self._fallthrough_variation - to._targets = dict() - for k, v in self._targets.items(): - to._targets[k] = copy.copy(v) - to._rules = copy.copy(self._rules) - - return to - - def on(self, on: bool) -> 'FlagBuilder': - """Sets targeting to be on or off for this flag. - - The effect of this depends on the rest of the flag configuration, just as it does on the - real LaunchDarkly dashboard. In the default configuration that you get from calling - :meth:`ldclient.integrations.test_data.TestData.flag()` with a new flag key, - the flag will return ``False`` whenever targeting is off, and ``True`` when - targeting is on. - - :param on: ``True`` if targeting should be on - :return: the flag builder - """ - self._on = on - return self - - def fallthrough_variation(self, variation: Union[bool, int]) -> 'FlagBuilder': - """Specifies the fallthrough variation. The fallthrough is the value - that is returned if targeting is on and the user was not matched by a more specific - target or rule. - - If the flag was previously configured with other variations and the variation - specified is a boolean, this also changes it to a boolean flag. - - :param bool|int variation: ``True`` or ``False`` or the desired fallthrough variation index: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder - """ - if isinstance(variation, bool): - self.boolean_flag()._fallthrough_variation = _variation_for_boolean(variation) - return self - else: - self._fallthrough_variation = variation - return self - - def off_variation(self, variation: Union[bool, int]) -> 'FlagBuilder': - """Specifies the fallthrough variation. This is the variation that is returned - whenever targeting is off. - - If the flag was previously configured with other variations and the variation - specified is a boolean, this also changes it to a boolean flag. - - :param bool|int variation: ``True`` or ``False`` or the desired off variation index: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder - """ - if isinstance(variation, bool): - self.boolean_flag()._off_variation = _variation_for_boolean(variation) - return self - else: - self._off_variation = variation - return self - - def boolean_flag(self) -> 'FlagBuilder': - """A shortcut for setting the flag to use the standard boolean configuration. - - This is the default for all new flags created with - :meth:`ldclient.integrations.test_data.TestData.flag()`. - - The flag will have two variations, ``True`` and ``False`` (in that order); - it will return ``False`` whenever targeting is off, and ``True`` when targeting is on - if no other settings specify otherwise. - - :return: the flag builder - """ - if self._is_boolean_flag(): - return self - else: - return self.variations(True, False).fallthrough_variation(TRUE_VARIATION_INDEX).off_variation(FALSE_VARIATION_INDEX) - - def _is_boolean_flag(self): - return len(self._variations) == 2 and self._variations[TRUE_VARIATION_INDEX] is True and self._variations[FALSE_VARIATION_INDEX] is False - - def variations(self, *variations) -> 'FlagBuilder': - """Changes the allowable variation values for the flag. - - The value may be of any valid JSON type. For instance, a boolean flag - normally has ``True, False``; a string-valued flag might have - ``'red', 'green'``; etc. - - **Example:** A single variation - :: - - td.flag('new-flag').variations(True) - - **Example:** Multiple variations - :: - - td.flag('new-flag').variations('red', 'green', 'blue') - - :param variations: the the desired variations - :return: the flag builder - """ - self._variations = list(variations) - - return self - - def variation_for_all(self, variation: Union[bool, int]) -> 'FlagBuilder': - """Sets the flag to always return the specified variation for all contexts. - - The variation is specified, targeting is switched on, and any existing targets or rules are removed. - The fallthrough variation is set to the specified value. The off variation is left unchanged. - - If the flag was previously configured with other variations and the variation specified is a boolean, - this also changes it to a boolean flag. - - :param bool|int variation: ``True`` or ``False`` or the desired variation index to return: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder - """ - if isinstance(variation, bool): - return self.boolean_flag().variation_for_all(_variation_for_boolean(variation)) - else: - return self.clear_rules().clear_targets().on(True).fallthrough_variation(variation) - - def value_for_all(self, value: Any) -> 'FlagBuilder': - """ - Sets the flag to always return the specified variation value for all users. - - The value may be of any JSON type. This method changes the flag to have only - a single variation, which is this value, and to return the same variation - regardless of whether targeting is on or off. Any existing targets or rules - are removed. - - :param value the desired value to be returned for all users - :return the flag builder - """ - return self.variations(value).variation_for_all(0).off_variation(0) - - def variation_for_user(self, user_key: str, variation: Union[bool, int]) -> 'FlagBuilder': - """Sets the flag to return the specified variation for a specific user key when targeting - is on. - - This has no effect when targeting is turned off for the flag. - - If the flag was previously configured with other variations and the variation specified is a boolean, - this also changes it to a boolean flag. - - :param user_key: a user key - :param bool|int variation: ``True`` or ``False`` or the desired variation index to return: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder - """ - return self.variation_for_key(Context.DEFAULT_KIND, user_key, variation) - - def variation_for_key(self, context_kind: str, context_key: str, variation: Union[bool, int]) -> 'FlagBuilder': - """Sets the flag to return the specified variation for a specific context, identified - by context kind and key, when targeting is on. - - This has no effect when targeting is turned off for the flag. - - If the flag was previously configured with other variations and the variation specified is a boolean, - this also changes it to a boolean flag. - - :param context_kind: the context kind - :param context_key: the context key - :param bool|int variation: ``True`` or ``False`` or the desired variation index to return: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder - """ - if isinstance(variation, bool): - # `variation` is True/False value - return self.boolean_flag().variation_for_key(context_kind, context_key, _variation_for_boolean(variation)) - - # `variation` specifies the index of the variation to set - targets = self._targets.get(context_kind) - if targets is None: - targets = {} - self._targets[context_kind] = targets - - for idx, var in enumerate(self._variations): - if idx == variation: - # If there is no set at the current variation, set it to be empty - target_for_variation = targets.get(idx) - if target_for_variation is None: - target_for_variation = set() - targets[idx] = target_for_variation - - # If key is not in the current variation set, add it - target_for_variation.add(context_key) - - else: - # Remove key from the other variation set if necessary - if idx in targets: - targets[idx].discard(context_key) - - return self - - def _add_rule(self, flag_rule_builder: 'FlagRuleBuilder'): - self._rules.append(flag_rule_builder) - - def if_match(self, attribute: str, *values) -> 'FlagRuleBuilder': - """Starts defining a flag rule, using the "is one of" operator. - - This is a shortcut for calling :meth:`ldclient.integrations.test_data.FlagBuilder.if_match_context()` - with "user" as the context kind. - - **Example:** create a rule that returns ``True`` if the name is "Patsy" or "Edina" - :: - - td.flag("flag") \\ - .if_match('name', 'Patsy', 'Edina') \\ - .then_return(True) - - :param attribute: the user attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - return self.if_match_context(Context.DEFAULT_KIND, attribute, *values) - - def if_match_context(self, context_kind: str, attribute: str, *values) -> 'FlagRuleBuilder': - """Starts defining a flag rule, using the "is one of" operator. This matching expression only - applies to contexts of a specific kind. - - **Example:** create a rule that returns ``True`` if the name attribute for the - company" context is "Ella" or "Monsoon": - :: - - td.flag("flag") \\ - .if_match_context('company', 'name', 'Ella', 'Monsoon') \\ - .then_return(True) - - :param context_kind: the context kind - :param attribute: the context attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - flag_rule_builder = FlagRuleBuilder(self) - return flag_rule_builder.and_match_context(context_kind, attribute, *values) - - def if_not_match(self, attribute: str, *values) -> 'FlagRuleBuilder': - """Starts defining a flag rule, using the "is not one of" operator. - - This is a shortcut for calling :meth:`ldclient.integrations.test_data.FlagBuilder.if_not_match_context()` - with "user" as the context kind. - - **Example:** create a rule that returns ``True`` if the name is neither "Saffron" nor "Bubble" - :: - - td.flag("flag") \\ - .if_not_match('name', 'Saffron', 'Bubble') \\ - .then_return(True) - - :param attribute: the user attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - return self.if_not_match_context(Context.DEFAULT_KIND, attribute, *values) - - def if_not_match_context(self, context_kind: str, attribute: str, *values) -> 'FlagRuleBuilder': - """Starts defining a flag rule, using the "is not one of" operator. This matching expression only - applies to contexts of a specific kind. - - **Example:** create a rule that returns ``True`` if the name attribute for the - "company" context is neither "Pendant" nor "Sterling Cooper": - :: - - td.flag("flag") \\ - .if_not_match('company', 'name', 'Pendant', 'Sterling Cooper') \\ - .then_return(True) - - :param context_kind: the context kind - :param attribute: the context attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - flag_rule_builder = FlagRuleBuilder(self) - return flag_rule_builder.and_not_match_context(context_kind, attribute, *values) - - def clear_rules(self) -> 'FlagBuilder': - """Removes any existing rules from the flag. - This undoes the effect of methods like - :meth:`ldclient.integrations.test_data.FlagBuilder.if_match()`. - - :return: the same flag builder - """ - self._rules = [] - return self - - def clear_targets(self) -> 'FlagBuilder': - """Removes any existing targets from the flag. - This undoes the effect of methods like - :meth:`ldclient.integrations.test_data.FlagBuilder.variation_for_user()`. - - :return: the same flag builder - """ - self._targets = {} - return self - - # Note that _build is private by convention, because we don't want developers to - # consider it part of the public API, but it is still called from TestData. - def _build(self, version: int) -> dict: - """Creates a dictionary representation of the flag - - :param version: the version number of the rule - :return: the dictionary representation of the flag - """ - base_flag_object = {'key': self._key, 'version': version, 'on': self._on, 'variations': self._variations, 'prerequisites': [], 'salt': ''} - - base_flag_object['offVariation'] = self._off_variation - base_flag_object['fallthrough'] = {'variation': self._fallthrough_variation} - - targets = [] - context_targets = [] - for target_context_kind, target_variations in self._targets.items(): - for var_index, target_keys in target_variations.items(): - if target_context_kind == Context.DEFAULT_KIND: - targets.append({'variation': var_index, 'values': sorted(list(target_keys))}) # sorting just for test determinacy - context_targets.append({'contextKind': target_context_kind, 'variation': var_index, 'values': []}) - else: - context_targets.append({'contextKind': target_context_kind, 'variation': var_index, 'values': sorted(list(target_keys))}) # sorting just for test determinacy - base_flag_object['targets'] = targets - base_flag_object['contextTargets'] = context_targets - - rules = [] - for idx, rule in enumerate(self._rules): - rules.append(rule._build(str(idx))) - base_flag_object['rules'] = rules - - return base_flag_object - - -class FlagRuleBuilder: - """ - A builder for feature flag rules to be used with :class:`ldclient.integrations.test_data.FlagBuilder`. - - In the LaunchDarkly model, a flag can have any number of rules, and a rule can have any number of - clauses. A clause is an individual test such as "name is 'X'". A rule matches a user if all of the - rule's clauses match the user. - - To start defining a rule, use one of the flag builder's matching methods such as - :meth:`ldclient.integrations.test_data.FlagBuilder.if_match()`. - This defines the first clause for the rule. Optionally, you may add more - clauses with the rule builder's methods such as - :meth:`ldclient.integrations.test_data.FlagRuleBuilder.and_match()` or - :meth:`ldclient.integrations.test_data.FlagRuleBuilder.and_not_match()`. - Finally, call :meth:`ldclient.integrations.test_data.FlagRuleBuilder.then_return()` - to finish defining the rule. - """ - - def __init__(self, flag_builder: FlagBuilder): - self._flag_builder = flag_builder - self._clauses = [] # type: List[dict] - self._variation = None # type: Optional[int] - - def and_match(self, attribute: str, *values) -> 'FlagRuleBuilder': - """Adds another clause, using the "is one of" operator. - - This is a shortcut for calling :meth:`ldclient.integrations.test_data.FlagRuleBuilder.and_match_context()` - with "user" as the context kind. - - **Example:** create a rule that returns ``True`` if the name is "Patsy" and the country is "gb" - :: - - td.flag('flag') \\ - .if_match('name', 'Patsy') \\ - .and_match('country', 'gb') \\ - .then_return(True) - - :param attribute: the user attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - return self.and_match_context(Context.DEFAULT_KIND, attribute, *values) - - def and_match_context(self, context_kind: str, attribute: str, *values) -> 'FlagRuleBuilder': - """Adds another clause, using the "is one of" operator. This matching expression only - applies to contexts of a specific kind. - - **Example:** create a rule that returns ``True`` if the name attribute for the - "company" context is "Ella", and the country attribute for the "company" context is "gb": - :: - - td.flag('flag') \\ - .if_match_context('company', 'name', 'Ella') \\ - .and_match_context('company', 'country', 'gb') \\ - .then_return(True) - - :param context_kind: the context kind - :param attribute: the context attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - self._clauses.append({'contextKind': context_kind, 'attribute': attribute, 'op': 'in', 'values': list(values), 'negate': False}) - return self - - def and_not_match(self, attribute: str, *values) -> 'FlagRuleBuilder': - """Adds another clause, using the "is not one of" operator. - - This is a shortcut for calling :meth:`ldclient.integrations.test_data.FlagRuleBuilder.and_not_match_context()` - with "user" as the context kind. - - **Example:** create a rule that returns ``True`` if the name is "Patsy" and the country is not "gb" - :: - - td.flag('flag') \\ - .if_match('name', 'Patsy') \\ - .and_not_match('country', 'gb') \\ - .then_return(True) - - :param attribute: the user attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - return self.and_not_match_context(Context.DEFAULT_KIND, attribute, *values) - - def and_not_match_context(self, context_kind: str, attribute: str, *values) -> 'FlagRuleBuilder': - """Adds another clause, using the "is not one of" operator. This matching expression only - applies to contexts of a specific kind. - - **Example:** create a rule that returns ``True`` if the name attribute for the - "company" context is "Ella", and the country attribute for the "company" context is not "gb": - :: - - td.flag('flag') \\ - .if_match_context('company', 'name', 'Ella') \\ - .and_not_match_context('company', 'country', 'gb') \\ - .then_return(True) - - :param context_kind: the context kind - :param attribute: the context attribute to match against - :param values: values to compare to - :return: the flag rule builder - """ - self._clauses.append({'contextKind': context_kind, 'attribute': attribute, 'op': 'in', 'values': list(values), 'negate': True}) - return self - - def then_return(self, variation: Union[bool, int]) -> 'FlagBuilder': - """Finishes defining the rule, specifying the result as either a boolean - or a variation index. - - If the flag was previously configured with other variations and the variation specified is a boolean, - this also changes it to a boolean flag. - - :param bool|int variation: ``True`` or ``False`` or the desired variation index: - ``0`` for the first, ``1`` for the second, etc. - :return: the flag builder with this rule added - """ - if isinstance(variation, bool): - self._flag_builder.boolean_flag() - return self.then_return(_variation_for_boolean(variation)) - else: - self._variation = variation - self._flag_builder._add_rule(self) - return self._flag_builder - - # Note that _build is private by convention, because we don't want developers to - # consider it part of the public API, but it is still called from FlagBuilder. - def _build(self, id: str) -> dict: - """Creates a dictionary representation of the rule - - :param id: the rule id - :return: the dictionary representation of the rule - """ - return {'id': 'rule' + id, 'variation': self._variation, 'clauses': self._clauses} diff --git a/ldclient/integrations/test_datav2.py b/ldclient/integrations/test_datav2.py index 3f68bdbf..23afed97 100644 --- a/ldclient/integrations/test_datav2.py +++ b/ldclient/integrations/test_datav2.py @@ -547,7 +547,7 @@ class TestDataV2: the data that the application has put into it using the ``update`` method. :: - from ldclient.impl.datasystem import config as datasystem_config + from ldclient import datasystem from ldclient.integrations.test_datav2 import TestDataV2 @@ -555,7 +555,7 @@ class TestDataV2: td.update(td.flag('flag-key-1').variation_for_all(True)) # Configure the data system with TestDataV2 as both initializer and synchronizer - data_config = datasystem_config.custom() + data_config = datasystem.custom() data_config.initializers([td.builder]) data_config.synchronizers(td.builder) diff --git a/ldclient/interfaces.py b/ldclient/interfaces.py index 76725565..7570c3ed 100644 --- a/ldclient/interfaces.py +++ b/ldclient/interfaces.py @@ -563,62 +563,6 @@ async def close(self) -> None: ... -class UpdateProcessor(ABC): - """ - Interface for the component that obtains feature flag data in some way and passes it to a - :class:`FeatureStore`. The built-in implementations of this are the client's standard streaming - or polling behavior. For testing purposes, there is also :func:`ldclient.integrations.Files.new_data_source()`. - """ - - def start(self): - """ - Starts the update processor in the background. Returns immediately and does not block. - """ - pass - - def stop(self): - """ - Stops the update processor. Can return before the background work stops. - """ - pass - - def initialized(self) -> bool: # type: ignore[empty-body] - """ - Returns whether the update processor has received feature flags and has initialized its feature store. - """ - - -class AsyncUpdateProcessor(ABC): - """ - Async interface for the component that obtains feature flag data and passes it to an - :class:`AsyncFeatureStore`, for use with :class:`ldclient.async_client.AsyncLDClient`. It mirrors - :class:`UpdateProcessor`, except ``stop`` is a coroutine. The built-in implementations are the - client's standard streaming or polling behavior. - - .. caution:: - This feature is experimental and should NOT be considered ready for production - use. It may change or be removed without notice and is not subject to backwards - compatibility guarantees. - """ - - def start(self): - """ - Starts the update processor in the background. Should return immediately and not block. - """ - pass - - async def stop(self): - """ - Stops the update processor. Awaiting the result ensures background work has stopped. - """ - pass - - def initialized(self) -> bool: # type: ignore[empty-body] - """ - Returns whether the update processor has received feature flags and has initialized its feature store. - """ - - class EventProcessor(ABC): """ Interface for the component that buffers analytics events and sends them to LaunchDarkly. @@ -688,52 +632,6 @@ async def stop(self): """ -class FeatureRequester(ABC): - """ - Interface for the component that acquires feature flag data in polling mode. The default - implementation can be replaced for testing purposes. - """ - - def get_all(self): - """ - Gets all feature flags. - """ - pass - - def get_all_data(self) -> Mapping[VersionedDataKind, Mapping[str, dict]]: - """ - Fetches all feature flag and segment data. - """ - raise NotImplementedError - - -class AsyncFeatureRequester(ABC): - """ - Async interface for the component that acquires feature flag data in polling - mode. The default implementation can be replaced for testing purposes. - - .. caution:: - This feature is experimental and should NOT be considered ready for production - use. It may change or be removed without notice and is not subject to backwards - compatibility guarantees. Pin to a specific minor version and review the changelog - before upgrading. - """ - - @abstractmethod - async def get_all_data(self) -> Mapping[VersionedDataKind, Mapping[str, dict]]: - """ - Fetches all feature flag and segment data. - """ - ... - - @abstractmethod - async def close(self) -> None: - """ - Releases any resources (such as an HTTP transport) owned by the requester. - """ - ... - - class DiagnosticDescription: """ Optional interface for components to describe their own configuration. @@ -1219,146 +1117,6 @@ def remove_listener(self, listener: Callable[[DataSourceStatus], None]): pass -class DataSourceUpdateSink(ABC): - """ - Interface that a data source implementation will use to push data into - the SDK. - - The data source interacts with this object, rather than manipulating - the data store directly, so that the SDK can perform any other - necessary operations that must happen when data is updated. - """ - - @abstractmethod - def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]): - """ - Initializes (or re-initializes) the store with the specified set of entities. Any - existing entries will be removed. Implementations can assume that this data set is up to - date-- there is no need to perform individual version comparisons between the existing - objects and the supplied features. - - If possible, the store should update the entire data set atomically. If that is not possible, - it should iterate through the outer hash and then the inner hash using the existing iteration - order of those hashes (the SDK will ensure that the items were inserted into the hashes in - the correct order), storing each item, and then delete any leftover items at the very end. - - :param all_data: All objects to be stored - """ - pass - - @abstractmethod - def upsert(self, kind: VersionedDataKind, item: dict): - """ - Attempt to add an entity, or update an existing entity with the same key. An update - should only succeed if the new item's version is greater than the old one; - otherwise, the method should do nothing. - - :param kind: The kind of object to update - :param item: The object to update or insert - """ - pass - - @abstractmethod - def delete(self, kind: VersionedDataKind, key: str, version: int): - """ - Attempt to delete an entity if it exists. Deletion should only succeed if the - version parameter is greater than the existing entity's version; otherwise, the - method should do nothing. - - :param kind: The kind of object to delete - :param key: The key of the object to be deleted - :param version: The version for the delete operation - """ - pass - - @abstractmethod - def update_status(self, new_state: DataSourceState, new_error: Optional[DataSourceErrorInfo]): - """ - Informs the SDK of a change in the data source's status. - - Data source implementations should use this method if they have any - concept of being in a valid state, a temporarily disconnected state, - or a permanently stopped state. - - If `new_state` is different from the previous state, and/or - `new_error` is non-null, the SDK will start returning the new status - (adding a timestamp for the change) from :class:`DataSourceStatusProvider.status`, and - will trigger status change events to any registered listeners. - - A special case is that if {new_state} is :class:`DataSourceState.INTERRUPTED`, but the - previous state was :class:`DataSourceState.INITIALIZING`, the state will remain at - :class:`DataSourceState.INITIALIZING` because :class:`DataSourceState.INTERRUPTED` is only meaningful - after a successful startup. - - :param new_state: The updated state of the data source - :param new_error: An optional error if the new state is an error condition - """ - pass - - -class AsyncDataSourceUpdateSink(ABC): - """ - Async interface that a data source implementation will use to push data into the SDK. - - .. caution:: - This feature is experimental and should NOT be considered ready for production - use. It may change or be removed without notice and is not subject to backwards - compatibility guarantees. Pin to a specific minor version and review the changelog - before upgrading. - - The data source interacts with this object, rather than manipulating the data store directly, - so that the SDK can perform any other necessary operations that must happen when data is - updated. - """ - - @abstractmethod - async def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]) -> None: - """ - Initializes (or re-initializes) the store with the specified set of entities. Any - existing entries will be removed. - - :param all_data: All objects to be stored - """ - pass - - @abstractmethod - async def upsert(self, kind: VersionedDataKind, item: dict) -> None: - """ - Attempt to add an entity, or update an existing entity with the same key. An update - should only succeed if the new item's version is greater than the old one; - otherwise, the method should do nothing. - - :param kind: The kind of object to update - :param item: The object to update or insert - """ - pass - - @abstractmethod - async def delete(self, kind: VersionedDataKind, key: str, version: int) -> None: - """ - Attempt to delete an entity if it exists. Deletion should only succeed if the - version parameter is greater than the existing entity's version; otherwise, the - method should do nothing. - - :param kind: The kind of object to delete - :param key: The key of the object to be deleted - :param version: The version for the delete operation - """ - pass - - @abstractmethod - def update_status(self, new_state: DataSourceState, new_error: Optional[DataSourceErrorInfo]) -> None: - """ - Informs the SDK of a change in the data source's status. - - This method is synchronous (not async) so it can be called from any context. - - :param new_state: The updated state of the data source - :param new_error: An optional error if the new state is an error condition - """ - pass - - class FlagChange: """ Change event fired when some aspect of the flag referenced by the key has changed. @@ -1586,40 +1344,6 @@ def __eq__(self, other): return False -class DataStoreUpdateSink(ABC): - """ - Interface that a data store implementation can use to report information - back to the SDK. - """ - - @abstractmethod - def status(self) -> DataStoreStatus: - """ - Inspect the data store's operational status. - """ - pass - - @abstractmethod - def update_status(self, status: DataStoreStatus): - """ - Reports a change in the data store's operational status. - - This is what makes the status monitoring mechanisms in - :class:`DataStoreStatusProvider` work. - - :param status: the updated status properties - """ - pass - - @property - @abstractmethod - def listeners(self) -> Listeners: - """ - Access the listeners associated with this sink instance. - """ - pass - - class DataStoreStatusProvider(ABC): """ An interface for querying the status of a persistent data store. diff --git a/ldclient/testing/impl/datasource/__init__.py b/ldclient/testing/impl/datasource/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/ldclient/testing/impl/datasource/test_async_polling.py b/ldclient/testing/impl/datasource/test_async_polling.py deleted file mode 100644 index 7a70c0b3..00000000 --- a/ldclient/testing/impl/datasource/test_async_polling.py +++ /dev/null @@ -1,717 +0,0 @@ -""" -Tests for AsyncFeatureRequesterImpl and AsyncPollingUpdateProcessor. -""" - -import asyncio -import logging -import ssl -import time -from unittest.mock import AsyncMock, MagicMock, patch - -import aiohttp -import pytest -from aiohttp.client_reqrep import ConnectionKey - -from ldclient.config import Config -from ldclient.impl.aio.transport_types import TransportResponse -from ldclient.impl.datasource.async_feature_requester import ( - AsyncFeatureRequesterImpl -) -from ldclient.impl.datasource.async_polling import AsyncPollingUpdateProcessor -from ldclient.impl.retry import ( - POLLING_RESET_SUCCESSES, - AfterConsecutiveSuccesses, - RetryState, - for_polling -) -from ldclient.impl.util import UnsuccessfulResponseException -from ldclient.interfaces import ( - AsyncDataSourceUpdateSink, - DataSourceErrorKind, - DataSourceState -) -from ldclient.testing.mock_async_components import ( - MockAsyncFeatureStore, - with_async_update_sink -) -from ldclient.testing.test_util import no_retry_jitter -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -# Sample data returned by a successful poll -SAMPLE_FLAGS = {'flagkey': {'key': 'flagkey', 'version': 1, 'deleted': False}} -SAMPLE_SEGMENTS = {'segkey': {'key': 'segkey', 'version': 1, 'deleted': False}} -SAMPLE_DATA = {FEATURES: SAMPLE_FLAGS, SEGMENTS: SAMPLE_SEGMENTS} - - -def make_config(**kwargs): - """Create a Config with the test SDK key.""" - return Config('SDK_KEY', **kwargs) - - -# aiohttp's connection errors read the connection key when they are turned -# into a string, which the data source does, so a real one is needed here. -_CONNECTION_KEY = ConnectionKey( - host='app.launchdarkly.com', - port=443, - is_ssl=True, - ssl=True, - proxy=None, - proxy_auth=None, - proxy_headers_hash=None, - server_hostname=None, -) - - -ONE_HOUR = 60 * 60 - - -def fast_retry_state(delay=0.001): - """A retry state whose every delay is ``delay``: small enough to skip the - real extended-regime wait, or large enough to prove a stop interrupts one.""" - return RetryState( - normal_initial_delay=delay, - normal_ceiling_delay=delay, - extended_initial_delay=delay, - extended_ceiling_delay=delay, - reset_policy=AfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES), - operating_cadence=delay, - ) - - -def make_processor(config=None, store=None, ready=None, requester=None, retry_state=None): - if config is None: - config = make_config() - if store is None: - store = MockAsyncFeatureStore() - if ready is None: - ready = asyncio.Event() - if requester is None: - requester = MagicMock() - requester.close = AsyncMock() - return AsyncPollingUpdateProcessor( - config=with_async_update_sink(config, store), - requester=requester, - store=store, - ready=ready, - retry_state=retry_state, - ) - - -def make_transport(*responses: TransportResponse): - """Create a stub transport whose request() returns the given responses in order.""" - transport = MagicMock() - transport.request = AsyncMock(side_effect=list(responses)) - return transport - - -class TestAsyncFeatureRequesterImpl: - @pytest.mark.asyncio - async def test_successful_response_returns_flags_and_segments(self): - import json - config = make_config() - transport = make_transport( - TransportResponse(200, {}, json.dumps({'flags': SAMPLE_FLAGS, 'segments': SAMPLE_SEGMENTS})) - ) - requester = AsyncFeatureRequesterImpl(config, transport) - - data = await requester.get_all_data() - - assert data[FEATURES] == SAMPLE_FLAGS - assert data[SEGMENTS] == SAMPLE_SEGMENTS - - @pytest.mark.asyncio - async def test_304_not_modified_returns_cached_data(self): - from ldclient.impl.datasource.async_feature_requester import CacheEntry - - config = make_config() - transport = make_transport(TransportResponse(304, {}, '')) - requester = AsyncFeatureRequesterImpl(config, transport) - - # Pre-populate the cache with a known etag and data - cached_data = {'flags': SAMPLE_FLAGS, 'segments': SAMPLE_SEGMENTS} - requester._cache[requester._poll_uri] = CacheEntry(data=cached_data, etag='"abc"') - - data = await requester.get_all_data() - - # 304 returns the cached data rather than None - assert data[FEATURES] == SAMPLE_FLAGS - assert data[SEGMENTS] == SAMPLE_SEGMENTS - # The cached etag is sent as If-None-Match - headers = transport.request.call_args.kwargs['headers'] - assert headers['If-None-Match'] == '"abc"' - - @pytest.mark.asyncio - async def test_etag_and_data_stored_after_successful_response(self): - config = make_config() - transport = make_transport( - TransportResponse(200, {'ETag': '"v1"'}, '{"flags": {}, "segments": {}}') - ) - requester = AsyncFeatureRequesterImpl(config, transport) - - await requester.get_all_data() - - cache_entry = requester._cache.get(requester._poll_uri) - assert cache_entry is not None - assert cache_entry.etag == '"v1"' - - @pytest.mark.asyncio - async def test_http_error_raises_unsuccessful_response_exception(self): - config = make_config() - transport = make_transport(TransportResponse(401, {}, '')) - requester = AsyncFeatureRequesterImpl(config, transport) - - with pytest.raises(UnsuccessfulResponseException) as exc_info: - await requester.get_all_data() - - assert exc_info.value.status == 401 - - @pytest.mark.asyncio - async def test_payload_filter_key_appended_to_uri(self): - config = Config('SDK_KEY', payload_filter_key='my-filter') - requester = AsyncFeatureRequesterImpl(config, MagicMock()) - - assert 'filter=my-filter' in requester._poll_uri - - @pytest.mark.asyncio - async def test_close_closes_owned_transport(self): - with patch('ldclient.impl.datasource.async_feature_requester.AsyncHTTPTransport') as MockTransport: - MockTransport.return_value.close = AsyncMock() - requester = AsyncFeatureRequesterImpl(make_config()) # no transport -> owns one - - await requester.close() - - MockTransport.return_value.close.assert_awaited_once() - - @pytest.mark.asyncio - async def test_close_does_not_close_injected_transport(self): - transport = MagicMock() - transport.close = AsyncMock() - requester = AsyncFeatureRequesterImpl(make_config(), transport) - - await requester.close() - - transport.close.assert_not_called() - - -class TestAsyncPollingUpdateProcessor: - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_successful_poll_initializes_store_and_sets_ready(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready) - - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - processor.start() - await asyncio.wait_for(ready.wait(), timeout=2.0) - - assert ready.is_set() - assert store.initialized - assert processor.initialized() - assert len(store.inits) >= 1 - assert store.inits[0] == SAMPLE_DATA - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_unexpected_http_error_keeps_polling_and_leaves_ready_unset(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready, retry_state=fast_retry_state()) - - mock_requester = AsyncMock(side_effect=UnsuccessfulResponseException(401)) - processor._requester.get_all_data = mock_requester - - processor.start() - await asyncio.sleep(0.1) - - # A rejected SDK key must not falsely unblock initialization, and it - # must not stop the poller. - assert not ready.is_set() - assert not processor.initialized() - assert mock_requester.call_count >= 2 - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_unexpected_http_error_moves_to_the_extended_regime(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - retry = fast_retry_state() - processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=UnsuccessfulResponseException(401)) - - processor.start() - await asyncio.sleep(0.05) - - assert retry._extended - - await processor.stop() - - @pytest.mark.asyncio - async def test_the_first_success_after_an_outage_polls_at_the_cadence(self): - # A backoff wait applies to a retry, not to every operation. The - # retry state carries the wait, so this reads it there rather than - # measuring elapsed time. - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - with no_retry_jitter(): - retry = for_polling(30) - processor = make_processor(config=config, store=store, ready=ready, retry_state=retry) - - processor._requester.get_all_data = AsyncMock(side_effect=UnsuccessfulResponseException(401)) - await processor._fetch_and_store() - assert retry.next_delay == 5 * 60 - - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - await processor._fetch_and_store() - assert retry.next_delay == 30 - assert retry._extended, "one success restores the cadence but does not reset" - - await processor._fetch_and_store() - assert retry.next_delay == 30 - assert not retry._extended, "two successes in a row reset the state" - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_recoverable_http_error_continues_polling(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready, retry_state=fast_retry_state()) - - call_count = 0 - - async def get_all_data(): - nonlocal call_count - call_count += 1 - if call_count < 3: - raise UnsuccessfulResponseException(500) - return SAMPLE_DATA - - processor._requester.get_all_data = get_all_data - - processor.start() - await asyncio.wait_for(ready.wait(), timeout=2.0) - - assert ready.is_set() - assert processor.initialized() - assert call_count >= 3 - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_general_exception_does_not_stop_polling(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready, retry_state=fast_retry_state()) - - call_count = 0 - - async def get_all_data(): - nonlocal call_count - call_count += 1 - if call_count < 3: - raise RuntimeError("transient error") - return SAMPLE_DATA - - processor._requester.get_all_data = get_all_data - - processor.start() - - # A generic error must NOT release start_wait; _ready stays unset until a - # later poll succeeds. Wait until the store is actually initialized - # (call_count reaches 3) to verify polling kept running. - async def wait_for_initialized(): - while not store.initialized: - await asyncio.sleep(0) - - await asyncio.wait_for(wait_for_initialized(), timeout=2.0) - - assert ready.is_set() - assert call_count >= 3 - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_general_exception_does_not_set_ready(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready) - - async def get_all_data(): - raise RuntimeError("transient error") - - processor._requester.get_all_data = get_all_data - - processor.start() - # Let several polls run; all raise. A transient error must not release - # start_wait (mirrors sync, which leaves _ready unset here). - await asyncio.sleep(0.05) - - assert not ready.is_set() - assert not processor.initialized() - - await processor.stop() - - @pytest.mark.parametrize( - "error", - [ - aiohttp.ClientConnectorCertificateError( - _CONNECTION_KEY, ssl.SSLCertVerificationError("self-signed certificate") - ), - aiohttp.ClientConnectorSSLError(_CONNECTION_KEY, OSError("handshake failed")), - ssl.SSLEOFError("EOF occurred in violation of protocol"), - ConnectionResetError(104, "reset by peer"), - ], - ids=["aiohttp-certificate", "aiohttp-tls", "peer-close-handshake", "reset"], - ) - @pytest.mark.asyncio - async def test_transport_failures_poll_again_at_the_cadence(self, error): - """No transport failure reaches the extended regime, an aiohttp - certificate failure included. Only an HTTP status can do that.""" - retry = for_polling(30) - processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=error) - - await processor._fetch_and_store() - assert retry.next_delay == 30 - assert not retry._extended - - @pytest.mark.asyncio - async def test_the_log_reports_the_growing_retry_delay(self, caplog): - """The message has to carry the real delay, so someone reading logs can - see the backoff working.""" - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_polling(30) - processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=UnsuccessfulResponseException(401)) - - await processor._fetch_and_store() - await processor._fetch_and_store() - - messages = [r.getMessage() for r in caplog.records] - assert messages == [ - "Received HTTP error 401 (invalid SDK key) for polling request - will retry in 300.0s", - "Received HTTP error 401 (invalid SDK key) for polling request - will retry in 600.0s", - ] - # An error a person has to fix is logged at error level, every time. - assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] - - @pytest.mark.asyncio - async def test_a_transport_error_reports_a_delay_and_keeps_its_stacktrace(self, caplog): - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_polling(30) - processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=ConnectionResetError(104, "reset by peer")) - - await processor._fetch_and_store() - - record = caplog.records[0] - assert record.getMessage() == "Error encountered when updating flags: [Errno 104] reset by peer - will retry in 30.0s" - # The handler has exited by the time this is logged, so the exception - # has to be carried explicitly for the traceback to survive. - assert record.exc_info is not None - - @pytest.mark.asyncio - async def test_stop_closes_requester(self): - processor = make_processor() - - await processor.stop() - - processor._requester.close.assert_awaited_once() - - @pytest.mark.asyncio - async def test_stop_awaits_poll_before_closing_transport(self): - # The in-flight poll must finish unwinding before the transport is - # closed, so we never close it out from under a live request. - order = [] - started = asyncio.Event() - - async def slow_poll(): - started.set() - try: - await asyncio.sleep(60) - except asyncio.CancelledError: - order.append('poll_done') - raise - - async def close(): - order.append('transport_closed') - - requester = MagicMock() - requester.get_all_data = slow_poll - requester.close = close - - processor = make_processor(requester=requester) - processor.start() - await asyncio.wait_for(started.wait(), timeout=1.0) - - await processor.stop() - - assert order == ['poll_done', 'transport_closed'] - - @pytest.mark.asyncio - async def test_an_extended_regime_wait_is_cut_short_by_stop(self): - """Shutdown must not sit through an hour-long backoff. The in-flight-poll - case is test_stop_cancels_polling_task_cleanly; this one stops while the - task is waiting between polls.""" - retry = fast_retry_state(ONE_HOUR) - processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock( - side_effect=UnsuccessfulResponseException(401) - ) - - processor.start() - # Confirm the wait under test really is long before measuring the stop. - deadline = time.time() + 2 - while retry.next_delay <= 60 and time.time() < deadline: - await asyncio.sleep(0.01) - assert retry.next_delay > 60, "the wait under test should be minutes long" - - started = time.time() - await processor.stop() - elapsed = time.time() - started - - assert elapsed < 2, "stop() took %.2fs" % elapsed - - @pytest.mark.asyncio - async def test_stop_cancels_polling_task_cleanly(self): - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - processor = make_processor(config=config, store=store, ready=ready) - - poll_count = 0 - - async def slow_poll(): - nonlocal poll_count - poll_count += 1 - await asyncio.sleep(60) # Would block indefinitely without cancel - - processor._requester.get_all_data = slow_poll - - processor.start() - await asyncio.sleep(0.05) # Let the task start - - # stop() should return promptly even though the poll is "sleeping" - await asyncio.wait_for(processor.stop(), timeout=1.0) - - # No further polls occur after stopping - await asyncio.sleep(0.05) - assert poll_count == 1 - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_unexpected_error_updates_sink_to_interrupted_never_off(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - - sink = MagicMock(spec=AsyncDataSourceUpdateSink) - config._data_source_update_sink = sink - - processor = make_processor(config=config, store=store, ready=ready, retry_state=fast_retry_state()) - processor._data_source_update_sink = sink - - processor._requester.get_all_data = AsyncMock( - side_effect=UnsuccessfulResponseException(403) - ) - - processor.start() - await asyncio.sleep(0.05) - - interrupted = [c for c in sink.update_status.call_args_list if c.args[0] == DataSourceState.INTERRUPTED] - assert len(interrupted) >= 1 - error_info = interrupted[0].args[1] - assert error_info.kind == DataSourceErrorKind.ERROR_RESPONSE - assert error_info.status_code == 403 - - assert not any(c.args[0] == DataSourceState.OFF for c in sink.update_status.call_args_list) - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_stop_updates_sink_to_off(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - config = make_config() - sink = MagicMock(spec=AsyncDataSourceUpdateSink) - config._data_source_update_sink = sink - - processor = make_processor(config=config) - processor._data_source_update_sink = sink - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - processor.start() - await processor.stop() - - assert any(c.args[0] == DataSourceState.OFF for c in sink.update_status.call_args_list) - - @pytest.mark.asyncio - async def test_a_poll_finishing_after_stop_reports_nothing(self): - """The poll still in flight when stop() ran must not report after OFF.""" - from ldclient.impl.datasource.async_status import ( - AsyncDataSourceUpdateSinkImpl - ) - from ldclient.impl.listeners import Listeners - - store = MockAsyncFeatureStore() - observed = [] - listeners = Listeners() - listeners.add(lambda status: observed.append(status.state)) - - config = make_config() - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, listeners, Listeners()) - - processor = make_processor(config=config, store=store) - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - await processor.stop() - await processor._fetch_and_store() - - assert observed == [DataSourceState.OFF] - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_valid_status_is_reported_before_ready_is_set(self, mock_interval): - # Mirrors go-server-sdk#442: a caller that wakes on readiness must not - # still be able to read INITIALIZING. - mock_interval.__get__ = MagicMock(return_value=0) - - from ldclient.impl.datasource.async_status import ( - AsyncDataSourceUpdateSinkImpl - ) - from ldclient.impl.listeners import Listeners - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - observed = [] - listeners = Listeners() - listeners.add(lambda status: observed.append((status.state, ready.is_set()))) - - config = make_config() - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, listeners, Listeners()) - - processor = make_processor(config=config, store=store, ready=ready) - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - processor.start() - await asyncio.wait_for(ready.wait(), timeout=2.0) - - assert observed[0] == (DataSourceState.VALID, False) - - await processor.stop() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_successful_poll_updates_sink_to_valid(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - store = MockAsyncFeatureStore() - ready = asyncio.Event() - config = make_config() - - # The sink's init() also marks the underlying store initialized, so the - # ready event fires (it gates on store.initialized) and ready.wait() - # below completes. - sink = MagicMock(spec=AsyncDataSourceUpdateSink) - - async def _init_and_store(data): - await store.init(data) - - sink.init = _init_and_store - config._data_source_update_sink = sink - - processor = make_processor(config=config, store=store, ready=ready) - processor._data_source_update_sink = sink - - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - processor.start() - await asyncio.wait_for(ready.wait(), timeout=2.0) - - valid_calls = [c for c in sink.update_status.call_args_list if c.args[0] == DataSourceState.VALID] - assert len(valid_calls) >= 1 - - await processor.stop() - - @pytest.mark.asyncio - async def test_initialized_returns_false_before_first_poll(self): - processor = make_processor() - assert not processor.initialized() - - @pytest.mark.asyncio - @patch('ldclient.config.Config.poll_interval', new_callable=MagicMock) - async def test_second_start_call_is_a_no_op(self, mock_interval): - mock_interval.__get__ = MagicMock(return_value=0) - - processor = make_processor() - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) - - processor.start() - task = processor._task - # The task guards against a second start; it logs and does nothing. - processor.start() - assert processor._task is task - - await processor.stop() - - @pytest.mark.asyncio - async def test_stop_closes_transport_when_cancelled_mid_wait(self): - # If the caller of stop() is cancelled while it waits for the poll to - # finish, the owned transport must still be closed (the close is in a - # finally), rather than leaking. - requester = MagicMock() - requester.close = AsyncMock() - processor = make_processor(requester=requester) - - # Replace the task's wait so it hangs until we cancel stop(). - waiting = asyncio.Event() - - async def hang(): - waiting.set() - await asyncio.Event().wait() - - processor._task.wait_stopped = hang # type: ignore[method-assign] - - stop_task = asyncio.create_task(processor.stop()) - await asyncio.wait_for(waiting.wait(), timeout=2.0) - stop_task.cancel() - with pytest.raises(asyncio.CancelledError): - await stop_task - - requester.close.assert_awaited_once() - - -def test_constructor_raises_without_update_sink(): - with pytest.raises(ValueError, match="data_source_update_sink"): - AsyncPollingUpdateProcessor(make_config(), MagicMock(), MockAsyncFeatureStore(), asyncio.Event()) diff --git a/ldclient/testing/impl/datasource/test_async_status.py b/ldclient/testing/impl/datasource/test_async_status.py deleted file mode 100644 index 25b8e635..00000000 --- a/ldclient/testing/impl/datasource/test_async_status.py +++ /dev/null @@ -1,367 +0,0 @@ -import pytest - -from ldclient.async_feature_store import AsyncInMemoryFeatureStore -from ldclient.impl.datasource.async_status import AsyncDataSourceUpdateSinkImpl -from ldclient.impl.datasource.status import DataSourceStatusProviderImpl -from ldclient.impl.listeners import Listeners -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState, - DataSourceStatus, - FlagChange -) -from ldclient.testing.builders import FlagBuilder, SegmentBuilder -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - - -def make_sink(store=None): - if store is None: - store = AsyncInMemoryFeatureStore() - status_listeners = Listeners() - flag_change_listeners = Listeners() - sink = AsyncDataSourceUpdateSinkImpl(store, status_listeners, flag_change_listeners) - return sink, status_listeners, flag_change_listeners - - -def make_flag(key, version=1): - return FlagBuilder(key).version(version).build() - - -def make_segment(key, version=1): - return SegmentBuilder(key).version(version).build() - - -class FlagChangeCapture: - """Captures FlagChange events delivered to a listener.""" - - def __init__(self): - self.keys = [] - - def __call__(self, change: FlagChange): - self.keys.append(change.key) - - -class StatusCapture: - """Captures DataSourceStatus events delivered to a status listener.""" - - def __init__(self): - self.statuses = [] - - def __call__(self, status: DataSourceStatus): - self.statuses.append(status) - - -class _FailingStore(AsyncInMemoryFeatureStore): - """Feature store whose reads and writes raise, to exercise the sink's - store-error monitoring.""" - - async def all(self, kind): - raise RuntimeError("boom") - - async def upsert(self, kind, item): - raise RuntimeError("boom") - - -@pytest.mark.asyncio -async def test_init_notifies_all_flag_change_listeners(): - sink, _, flag_listeners = make_sink() - - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag_a = make_flag('flag-a') - flag_b = make_flag('flag-b') - - await sink.init({ - FEATURES: { - 'flag-a': flag_a.to_json_dict(), - 'flag-b': flag_b.to_json_dict(), - }, - SEGMENTS: {}, - }) - - assert sorted(capture.keys) == ['flag-a', 'flag-b'] - - -@pytest.mark.asyncio -async def test_init_does_not_notify_flag_listeners_when_none_registered(): - sink, _, flag_listeners = make_sink() - - # No listener added — calling init should not raise and should be a no-op - # for notifications. - flag_a = make_flag('flag-a') - await sink.init({FEATURES: {'flag-a': flag_a.to_json_dict()}, SEGMENTS: {}}) - # No assertions needed — just confirming no error and no listener calls. - - -@pytest.mark.asyncio -async def test_init_notifies_listeners_for_changed_flags_on_reinit(): - sink, _, flag_listeners = make_sink() - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag_v1 = make_flag('flag-a', version=1) - await sink.init({FEATURES: {'flag-a': flag_v1.to_json_dict()}, SEGMENTS: {}}) - capture.keys.clear() - - flag_v2 = make_flag('flag-a', version=2) - flag_new = make_flag('flag-b', version=1) - await sink.init({ - FEATURES: { - 'flag-a': flag_v2.to_json_dict(), - 'flag-b': flag_new.to_json_dict(), - }, - SEGMENTS: {}, - }) - - assert sorted(capture.keys) == ['flag-a', 'flag-b'] - - -@pytest.mark.asyncio -async def test_upsert_flag_notifies_listener(): - sink, _, flag_listeners = make_sink() - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag = make_flag('my-flag', version=1) - await sink.upsert(FEATURES, flag.to_json_dict()) - - assert capture.keys == ['my-flag'] - - -@pytest.mark.asyncio -async def test_upsert_segment_does_not_notify_flag_listener(): - sink, _, flag_listeners = make_sink() - capture = FlagChangeCapture() - flag_listeners.add(capture) - - segment = make_segment('my-segment', version=1) - await sink.upsert(SEGMENTS, segment.to_json_dict()) - - assert capture.keys == [] - - -@pytest.mark.asyncio -async def test_upsert_same_version_does_not_notify(): - store = AsyncInMemoryFeatureStore() - sink, _, flag_listeners = make_sink(store) - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag_v1 = make_flag('my-flag', version=1) - - # Insert the flag at version 1. - await sink.upsert(FEATURES, flag_v1.to_json_dict()) - assert capture.keys == ['my-flag'] - capture.keys.clear() - - # Upsert the same version — store rejects it, no notification expected. - await sink.upsert(FEATURES, flag_v1.to_json_dict()) - assert capture.keys == [] - - -@pytest.mark.asyncio -async def test_upsert_older_version_does_not_notify(): - store = AsyncInMemoryFeatureStore() - sink, _, flag_listeners = make_sink(store) - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag_v2 = make_flag('my-flag', version=2) - await sink.upsert(FEATURES, flag_v2.to_json_dict()) - capture.keys.clear() - - flag_v1 = make_flag('my-flag', version=1) - await sink.upsert(FEATURES, flag_v1.to_json_dict()) - assert capture.keys == [] - - -@pytest.mark.asyncio -async def test_upsert_newer_version_notifies(): - store = AsyncInMemoryFeatureStore() - sink, _, flag_listeners = make_sink(store) - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag_v1 = make_flag('my-flag', version=1) - await sink.upsert(FEATURES, flag_v1.to_json_dict()) - capture.keys.clear() - - flag_v2 = make_flag('my-flag', version=2) - await sink.upsert(FEATURES, flag_v2.to_json_dict()) - assert capture.keys == ['my-flag'] - - -@pytest.mark.asyncio -async def test_delete_flag_notifies_listener(): - sink, _, flag_listeners = make_sink() - capture = FlagChangeCapture() - flag_listeners.add(capture) - - flag = make_flag('my-flag', version=1) - await sink.upsert(FEATURES, flag.to_json_dict()) - capture.keys.clear() - - await sink.delete(FEATURES, 'my-flag', version=2) - - assert capture.keys == ['my-flag'] - - -@pytest.mark.asyncio -async def test_delete_segment_does_not_notify_flag_listener(): - sink, _, flag_listeners = make_sink() - capture = FlagChangeCapture() - flag_listeners.add(capture) - - segment = make_segment('my-segment', version=1) - await sink.upsert(SEGMENTS, segment.to_json_dict()) - capture.keys.clear() - - await sink.delete(SEGMENTS, 'my-segment', version=2) - - assert capture.keys == [] - - -@pytest.mark.asyncio -async def test_update_status_broadcasts_to_status_listeners(): - sink, status_listeners, _ = make_sink() - capture = StatusCapture() - status_listeners.add(capture) - - sink.update_status(DataSourceState.VALID, None) - - assert len(capture.statuses) == 1 - assert capture.statuses[0].state == DataSourceState.VALID - - -@pytest.mark.asyncio -async def test_update_status_interrupted_during_init_stays_initializing(): - sink, status_listeners, _ = make_sink() - capture = StatusCapture() - status_listeners.add(capture) - - # State starts as INITIALIZING; INTERRUPTED should be coerced back. - sink.update_status(DataSourceState.INTERRUPTED, None) - - assert len(capture.statuses) == 0 # state unchanged → no broadcast - - -@pytest.mark.asyncio -async def test_update_status_no_broadcast_when_unchanged(): - sink, status_listeners, _ = make_sink() - - # Transition to VALID first. - sink.update_status(DataSourceState.VALID, None) - - capture = StatusCapture() - status_listeners.add(capture) - - # Calling with the same state and no error should not broadcast. - sink.update_status(DataSourceState.VALID, None) - - assert capture.statuses == [] - - -@pytest.mark.asyncio -async def test_update_status_broadcasts_error_even_with_same_state(): - sink, status_listeners, _ = make_sink() - sink.update_status(DataSourceState.VALID, None) - - capture = StatusCapture() - status_listeners.add(capture) - - error = DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, 0.0, "connection lost") - sink.update_status(DataSourceState.VALID, error) - - assert len(capture.statuses) == 1 - assert capture.statuses[0].error is error - - -@pytest.mark.asyncio -async def test_status_provider_delegates_to_sink(): - sink, status_listeners, _ = make_sink() - provider = DataSourceStatusProviderImpl(status_listeners, sink) - - assert provider.status.state == DataSourceState.INITIALIZING - - sink.update_status(DataSourceState.VALID, None) - - assert provider.status.state == DataSourceState.VALID - - -@pytest.mark.asyncio -async def test_status_provider_add_remove_listener(): - sink, status_listeners, _ = make_sink() - provider = DataSourceStatusProviderImpl(status_listeners, sink) - - capture = StatusCapture() - provider.add_listener(capture) - - sink.update_status(DataSourceState.VALID, None) - assert len(capture.statuses) == 1 - - provider.remove_listener(capture) - sink.update_status(DataSourceState.OFF, None) - assert len(capture.statuses) == 1 # listener was removed, no new events - - -@pytest.mark.asyncio -async def test_init_records_store_error_when_prior_read_fails(): - # A flag-change listener must be registered so init reads prior data via - # all(); that read is monitored, so a failure records STORE_ERROR. - sink, status_listeners, flag_listeners = make_sink(_FailingStore()) - flag_listeners.add(FlagChangeCapture()) - status_capture = StatusCapture() - status_listeners.add(status_capture) - - with pytest.raises(RuntimeError): - await sink.init({FEATURES: {}, SEGMENTS: {}}) - - assert len(status_capture.statuses) == 1 - assert status_capture.statuses[0].error.kind == DataSourceErrorKind.STORE_ERROR - - -@pytest.mark.asyncio -async def test_upsert_records_store_error_on_failure(): - sink, status_listeners, _ = make_sink(_FailingStore()) - status_capture = StatusCapture() - status_listeners.add(status_capture) - - with pytest.raises(RuntimeError): - await sink.upsert(FEATURES, make_flag('flag-a').to_json_dict()) - - assert len(status_capture.statuses) == 1 - assert status_capture.statuses[0].error.kind == DataSourceErrorKind.STORE_ERROR - - -@pytest.mark.asyncio -async def test_update_status_off_is_terminal(): - sink, status_listeners, _ = make_sink() - status_capture = StatusCapture() - status_listeners.add(status_capture) - - sink.update_status(DataSourceState.VALID, None) - sink.update_status(DataSourceState.OFF, None) - - # A poll or stream connection still in flight when the data source stopped. - sink.update_status(DataSourceState.VALID, None) - sink.update_status(DataSourceState.INTERRUPTED, DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, 1000, 'late')) - - assert sink.status.state == DataSourceState.OFF - assert sink.status.error is None - assert [status.state for status in status_capture.statuses] == [DataSourceState.VALID, DataSourceState.OFF] - - -@pytest.mark.asyncio -async def test_store_error_after_off_reports_nothing(): - sink, status_listeners, _ = make_sink(_FailingStore()) - status_capture = StatusCapture() - status_listeners.add(status_capture) - sink.update_status(DataSourceState.OFF, None) - - with pytest.raises(RuntimeError): - await sink.upsert(FEATURES, make_flag('flag-a').to_json_dict()) - - assert sink.status.state == DataSourceState.OFF - assert [status.state for status in status_capture.statuses] == [DataSourceState.OFF] diff --git a/ldclient/testing/impl/datasource/test_async_streaming.py b/ldclient/testing/impl/datasource/test_async_streaming.py deleted file mode 100644 index 0ab1c66c..00000000 --- a/ldclient/testing/impl/datasource/test_async_streaming.py +++ /dev/null @@ -1,943 +0,0 @@ -""" -Tests for AsyncStreamingUpdateProcessor. - -These tests inject a mock SSE factory that yields pre-configured actions -rather than making real network connections. -""" - -import asyncio -import json -import logging -import ssl -import time -from unittest import mock - -import aiohttp -import pytest -from aiohttp.client_reqrep import ConnectionKey - -from ldclient.config import Config -from ldclient.impl.datasource import async_streaming -from ldclient.impl.datasource.async_streaming import ( - AsyncStreamingUpdateProcessor -) -from ldclient.impl.model import ModelEntity -from ldclient.impl.retry import ( - EXTENDED_CEILING_DELAY, - EXTENDED_INITIAL_DELAY, - NORMAL_STREAMING_CEILING_DELAY, - STREAMING_RESET_INTERVAL, - AfterHealthyFor, - RetryState, - for_streaming -) -from ldclient.interfaces import DataSourceErrorKind, DataSourceState -from ldclient.testing.builders import FlagBuilder, SegmentBuilder -from ldclient.testing.mock_async_components import ( - MockAsyncFeatureStore, - with_async_update_sink -) -from ldclient.testing.test_util import ( - no_retry_jitter, - record_healthy_windows, - ticking_clock -) -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - - -def _item_dict(item): - """Convert a model entity (FeatureFlag, Segment, etc.) to a plain dict.""" - return item.to_json_dict() if isinstance(item, ModelEntity) else item - - -def _make_config(**kwargs): - return Config(sdk_key='sdk-key', **kwargs) - - -def _make_put_data(flags=None, segments=None): - flags = flags or {} - segments = segments or {} - return json.dumps({"data": {"flags": flags, "segments": segments}}) - - -def _make_patch_data(kind, item): - path = '%s%s' % (kind.stream_api_path, item['key']) - return json.dumps({"path": path, "data": item}) - - -def _make_delete_data(kind, key, version): - path = '%s%s' % (kind.stream_api_path, key) - return json.dumps({"path": path, "version": version}) - - -# The processor matches actions with isinstance() against the real -# ld_eventsource action classes, so the fakes must be real instances. -from ld_eventsource.actions import Event as _RealEvent # noqa: E402 -from ld_eventsource.actions import Fault as _RealFault # noqa: E402 -from ld_eventsource.actions import Start as _RealStart # noqa: E402 - - -def _event(event_type: str, data: str) -> _RealEvent: - return _RealEvent(event=event_type, data=data) - - -def _fault(error=None) -> _RealFault: - return _RealFault(error=error) - - -def _start() -> _RealStart: - return _RealStart(headers={}) - - -async def _actions_generator(actions: list): - """Yield a fixed sequence of actions then hang (simulates a live stream).""" - for action in actions: - yield action - # Block forever so the processor's loop doesn't exit until cancelled. - await asyncio.Event().wait() - - -def _retry_state_with(policy: AfterHealthyFor) -> RetryState: - """A retry state with tiny delays and a caller-supplied reset policy, so a - test can watch the window.""" - return RetryState( - normal_initial_delay=0.001, - normal_ceiling_delay=0.001, - extended_initial_delay=0.001, - extended_ceiling_delay=0.001, - reset_policy=policy, - ) - - -ONE_HOUR = 60 * 60 - - -def _fast_retry_state(delay: float = 0.001) -> RetryState: - """A retry state whose every delay is ``delay``: small enough to skip the - real extended-regime wait, or large enough to prove a stop interrupts one.""" - return RetryState( - normal_initial_delay=delay, - normal_ceiling_delay=delay, - extended_initial_delay=delay, - extended_ceiling_delay=delay, - reset_policy=AfterHealthyFor(STREAMING_RESET_INTERVAL), - ) - - -# aiohttp's connection errors read the connection key when they are turned -# into a string, which the data source does, so a real one is needed here. -_CONNECTION_KEY = ConnectionKey( - host='stream.launchdarkly.com', - port=443, - is_ssl=True, - ssl=True, - proxy=None, - proxy_auth=None, - proxy_headers_hash=None, - server_hostname=None, -) - - -def _zero_delay_retry_state() -> RetryState: - """A retry state whose normal regime waits no time at all, so a test can - drive ``_handle_error`` without a real sleep. The extended bounds stay - real, so a misclassification still shows up in ``max_delay``.""" - return RetryState( - normal_initial_delay=0, - normal_ceiling_delay=NORMAL_STREAMING_CEILING_DELAY, - extended_initial_delay=EXTENDED_INITIAL_DELAY, - extended_ceiling_delay=EXTENDED_CEILING_DELAY, - reset_policy=AfterHealthyFor(STREAMING_RESET_INTERVAL), - ) - - -class _MockSSE: - """Stand-in for AsyncSSEClient exposing the surface the processor uses.""" - - def __init__(self, actions: list): - self._actions = actions - self.interrupted = False - self.closed = False - self.next_retry_delay = 0.0 - - async def interrupt(self): - self.interrupted = True - - async def close(self): - self.closed = True - - @property - def all(self): - return _actions_generator(self._actions) - - -class _MockSSEFactory: - """Stand-in for AsyncSSEFactory; create() returns a _MockSSE.""" - - def __init__(self, actions: list): - self._actions = actions - self.created: list = [] - self.sdk_managed_retry: list = [] - - def create(self, url: str, initial_retry_delay: float, sdk_managed_retry: bool = False) -> _MockSSE: - sse = _MockSSE(self._actions) - self.created.append(sse) - self.sdk_managed_retry.append(sdk_managed_retry) - return sse - - -def _make_processor(actions, config=None, store=None, ready_event=None, diag=None, retry_state=None): - config = config or _make_config() - store = store or MockAsyncFeatureStore() - ready_event = ready_event or asyncio.Event() - factory = _MockSSEFactory(actions) - proc = AsyncStreamingUpdateProcessor(with_async_update_sink(config, store), store, ready_event, diag, factory, retry_state=retry_state) - return proc, store, ready_event, factory - - -async def _run_with_actions(actions: list, config=None, store=None, ready_event=None, - diag=None, extra_ready_timeout=3.0, retry_state=None): - """Run the processor against a fake SSE action sequence. - - Starts the processor and waits for the ready event (up to - *extra_ready_timeout* seconds), then returns - ``(processor, store, ready_event, factory)``. - """ - proc, store, ready, factory = _make_processor(actions, config, store, ready_event, diag, retry_state) - proc.start() - try: - await asyncio.wait_for(ready.wait(), timeout=extra_ready_timeout) - except asyncio.TimeoutError: - pass # some tests expect ready NOT to be set - return proc, store, ready, factory - - -async def _wait_until(pred, timeout=2.0): - loop = asyncio.get_event_loop() - deadline = loop.time() + timeout - while not pred(): - assert loop.time() < deadline, "condition was not met in time" - await asyncio.sleep(0.005) - - -@pytest.mark.asyncio -async def test_put_event_initializes_store_and_sets_ready(): - flag = FlagBuilder('f1').version(1).build() - segment = SegmentBuilder('s1').version(1).build() - put_data = _make_put_data( - flags={'f1': _item_dict(flag)}, - segments={'s1': _item_dict(segment)}, - ) - actions = [_start(), _event('put', put_data)] - - proc, store, ready, _ = await _run_with_actions(actions) - - assert ready.is_set() - assert store.initialized - stored_flag = await store.get(FEATURES, 'f1') - assert stored_flag is not None - assert stored_flag['version'] == 1 - - stored_seg = await store.get(SEGMENTS, 's1') - assert stored_seg is not None - assert stored_seg['version'] == 1 - - await proc.stop() - - -@pytest.mark.asyncio -async def test_patch_event_upserts_to_store(): - flagv1 = FlagBuilder('f1').version(1).build() - flagv2 = FlagBuilder('f1').version(2).build() - put_data = _make_put_data(flags={'f1': _item_dict(flagv1)}) - patch_data = _make_patch_data(FEATURES, _item_dict(flagv2)) - actions = [_start(), _event('put', put_data), _event('patch', patch_data)] - - proc, store, ready, _ = await _run_with_actions(actions) - - # Give the event loop a beat for the patch to process after ready fires. - await asyncio.sleep(0.05) - - stored = await store.get(FEATURES, 'f1') - assert stored is not None - assert stored['version'] == 2 - - await proc.stop() - - -@pytest.mark.asyncio -async def test_delete_event_removes_item_from_store(): - flagv1 = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flagv1)}) - delete_data = _make_delete_data(FEATURES, 'f1', 2) - actions = [_start(), _event('put', put_data), _event('delete', delete_data)] - - proc, store, ready, _ = await _run_with_actions(actions) - - await asyncio.sleep(0.05) - - deleted = await store.get(FEATURES, 'f1') - assert deleted is None - - await proc.stop() - - -@pytest.mark.asyncio -async def test_fault_with_error_does_not_set_ready_by_itself(): - """A Fault that arrives before any put must not mark the processor as initialized.""" - from ld_eventsource.errors import HTTPStatusError - - # Provide only a recoverable fault (503) — no put follows. - actions = [_start(), _fault(error=HTTPStatusError(503))] - - # Use a short timeout so the test doesn't hang. - proc, store, ready, _ = await _run_with_actions(actions, extra_ready_timeout=0.2) - - # Ready should NOT have been set by the fault alone. - assert not ready.is_set() - assert not store.initialized - - await proc.stop() - - -@pytest.mark.asyncio -async def test_server_close_backs_off_and_does_not_stop_the_processor(): - """A Fault with error=None is the server closing a connection it normally - leaves open. The SDK backs off rather than reconnecting at once, but the - processor keeps running.""" - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [ - _start(), - _event('put', put_data), - _fault(error=None), # clean close by the server - ] - - retry = _fast_retry_state() - proc, store, ready, factory = _make_processor(actions, retry_state=retry) - proc.start() - await asyncio.wait_for(ready.wait(), timeout=3.0) - await _wait_until(lambda: retry._attempts >= 1) - - assert store.initialized - assert not factory.created[0].closed - assert not retry._extended - - await proc.stop() - - -@pytest.mark.asyncio -async def test_server_close_reports_a_network_error(): - from ldclient.impl.datasource.async_status import ( - AsyncDataSourceUpdateSinkImpl - ) - from ldclient.impl.listeners import Listeners - - store = MockAsyncFeatureStore() - statuses = [] - listeners = Listeners() - listeners.add(lambda s: statuses.append(s)) - - config = _make_config() - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, listeners, Listeners()) - - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [_start(), _event('put', put_data), _fault(error=None)] - - proc, store, ready, _ = _make_processor(actions, config=config, store=store, retry_state=_fast_retry_state()) - proc.start() - await _wait_until(lambda: any(s.state == DataSourceState.INTERRUPTED for s in statuses)) - - interrupted = [s for s in statuses if s.state == DataSourceState.INTERRUPTED] - assert interrupted[0].error is not None - assert interrupted[0].error.kind == DataSourceErrorKind.NETWORK_ERROR - - await proc.stop() - - -@pytest.mark.asyncio -async def test_repeated_server_closes_stay_on_the_normal_curve(): - """A load balancer draining during a rolling deploy closes streams - cleanly, over and over. That must never reach the extended regime.""" - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [] - for _ in range(10): - actions += [_start(), _event('put', put_data), _fault(error=None)] - - retry = _fast_retry_state() - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - await _wait_until(lambda: retry._attempts >= 10, timeout=5.0) - - assert not retry._extended - assert retry._max_delay == _fast_retry_state()._max_delay - - await proc.stop() - - -@pytest.mark.asyncio -async def test_our_own_interrupt_is_not_counted_as_a_server_close(): - """Bad JSON makes the SDK drop the connection itself. The SSE client then - reports that close as a Fault with no error, and counting it would record - the same failure twice and wait twice.""" - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [ - _start(), - _event('put', put_data), - _event('patch', 'not valid json'), - _fault(error=None), # the close our own interrupt caused - ] - - retry = _fast_retry_state() - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - await _wait_until(lambda: retry._attempts >= 1) - await asyncio.sleep(0.1) - - assert retry._attempts == 1 - - await proc.stop() - - -@pytest.mark.asyncio -async def test_a_leaked_interrupt_flag_does_not_swallow_a_server_close(): - """interrupt() is a no-op when the connection has already gone, so no - Fault arrives to clear the flag. A new connection must clear it, or the - next genuine close is recorded as ours and the backoff is skipped.""" - put_data = _make_put_data() - actions = [ - _start(), - _event('put', put_data), - _fault(error=None), # a close the SDK did not ask for - ] - - retry = _fast_retry_state() - proc, _, _, _ = _make_processor(actions, retry_state=retry) - proc._interrupted_by_sdk = True - proc.start() - await _wait_until(lambda: retry._attempts >= 1) - await asyncio.sleep(0.1) - - assert retry._attempts == 1 - - await proc.stop() - - -@pytest.mark.asyncio -async def test_unexpected_http_error_keeps_the_processor_running(): - """A rejected SDK key is retried like any other failure. The state never - goes OFF, and initialization is not falsely unblocked.""" - from ld_eventsource.errors import HTTPStatusError - - from ldclient.impl.datasource.async_status import ( - AsyncDataSourceUpdateSinkImpl - ) - from ldclient.impl.listeners import Listeners - - store = MockAsyncFeatureStore() - statuses = [] - listeners = Listeners() - listeners.add(lambda s: statuses.append(s)) - - config = _make_config() - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, listeners, Listeners()) - - actions = [_start(), _fault(error=HTTPStatusError(401))] - - proc, store, ready, factory = await _run_with_actions( - actions, config=config, store=store, extra_ready_timeout=0.2, - retry_state=_fast_retry_state(), - ) - - assert not ready.is_set() - assert not proc.initialized() - assert not factory.created[0].closed - assert all(s.state != DataSourceState.OFF for s in statuses) - assert any( - s.error is not None - and s.error.kind == DataSourceErrorKind.ERROR_RESPONSE - and s.error.status_code == 401 - for s in statuses - ) - - await proc.stop() - - -@pytest.mark.asyncio -async def test_unexpected_http_error_moves_to_the_extended_regime(): - from ld_eventsource.errors import HTTPStatusError - - actions = [_start(), _fault(error=HTTPStatusError(401))] - retry = _fast_retry_state() - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - await _wait_until(lambda: retry._extended) - - await proc.stop() - - -@pytest.mark.asyncio -async def test_normal_http_error_stays_in_the_normal_regime(): - from ld_eventsource.errors import HTTPStatusError - - actions = [_start(), _fault(error=HTTPStatusError(503))] - retry = _fast_retry_state() - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - await _wait_until(lambda: retry._attempts >= 1) - - assert not retry._extended - - await proc.stop() - - -@pytest.mark.parametrize( - "error", - [ - aiohttp.ClientConnectorCertificateError( - _CONNECTION_KEY, ssl.SSLCertVerificationError("self-signed certificate") - ), - aiohttp.ClientConnectorSSLError(_CONNECTION_KEY, OSError("handshake failed")), - ssl.SSLEOFError("EOF occurred in violation of protocol"), - ConnectionResetError(104, "reset by peer"), - ], - ids=["aiohttp-certificate", "aiohttp-tls", "peer-close-handshake", "reset"], -) -@pytest.mark.asyncio -async def test_transport_failures_stay_in_the_normal_regime(error): - """No transport failure reaches the extended regime, an aiohttp - certificate failure included. Only an HTTP status can do that.""" - retry = _zero_delay_retry_state() - proc, store, ready, _ = _make_processor([], retry_state=retry) - proc._running = True - - # A misclassification would wait five minutes here, so bound the wait - # rather than let the test hang. - assert await asyncio.wait_for(proc._handle_error(error), timeout=2.0) - - assert not retry._extended - assert retry._max_delay == NORMAL_STREAMING_CEILING_DELAY - - -class _NoSleep: - """Stands in for the ``asyncio`` module inside async_streaming, so the wait - in _handle_error returns at once. ``sleep`` is all that module uses.""" - - def __init__(self): - self.slept: list = [] - - async def sleep(self, seconds): - self.slept.append(seconds) - - -@pytest.mark.asyncio -async def test_the_log_reports_the_growing_retry_delay(caplog): - """The message has to carry the real delay, so someone reading logs can see - the backoff working. The vaguer wording it replaced could not show this.""" - from ld_eventsource.errors import HTTPStatusError - - caplog.set_level(logging.WARNING) - no_sleep = _NoSleep() - - with no_retry_jitter(), mock.patch.object(async_streaming, 'asyncio', no_sleep): - retry = for_streaming(1) - proc, store, ready, _ = _make_processor([], retry_state=retry) - proc._running = True - - await proc._handle_error(HTTPStatusError(401)) - await proc._handle_error(HTTPStatusError(401)) - - messages = [r.getMessage() for r in caplog.records] - assert messages == [ - "Received HTTP error 401 (invalid SDK key) for stream connection - will retry in 300.0s", - "Received HTTP error 401 (invalid SDK key) for stream connection - will retry in 600.0s", - ] - # An error a person has to fix is logged at error level, every time. - assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] - # The reported delay is the one actually waited. - assert no_sleep.slept == [5 * 60, 10 * 60] - - -@pytest.mark.asyncio -async def test_the_processor_asks_the_factory_to_leave_the_delay_to_the_sdk(): - proc, store, ready, factory = _make_processor([]) - proc.start() - await _wait_until(lambda: len(factory.created) > 0) - - assert factory.sdk_managed_retry == [True] - - await proc.stop() - - -@pytest.mark.asyncio -async def test_several_messages_on_one_stream_do_not_extend_the_reset_window(): - """The window starts at the first message and stays there, however many - more arrive on the same stream.""" - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - patch_data = _make_patch_data(FEATURES, _item_dict(FlagBuilder('f1').version(2).build())) - actions = [_start(), _event('put', put_data), _event('patch', patch_data)] - - policy = AfterHealthyFor(STREAMING_RESET_INTERVAL) - retry = _retry_state_with(policy) - # The clock moves on every read, so a window that had been restarted reads - # back as a different time. - windows = record_healthy_windows(policy) - - with ticking_clock(): - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - await _wait_until(lambda: len(windows) >= 2) - await proc.stop() - - assert len(set(windows)) == 1, "the window moved between messages" - - -@pytest.mark.asyncio -async def test_a_fresh_stream_starts_a_new_reset_window(): - """A stream teardown clears the window through record_failure, so the next - stream measures its own stretch rather than inheriting the old one.""" - from ld_eventsource.errors import HTTPStatusError - - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [ - _start(), - _event('put', put_data), - _fault(error=HTTPStatusError(503)), - _start(), - _event('put', put_data), - ] - - policy = AfterHealthyFor(STREAMING_RESET_INTERVAL) - retry = _retry_state_with(policy) - windows = record_healthy_windows(policy) - - with ticking_clock(): - proc, store, ready, _ = _make_processor(actions, retry_state=retry) - proc.start() - # One put per stream, so two signals in all. - await _wait_until(lambda: len(windows) >= 2) - await proc.stop() - - assert len(set(windows)) == 2, "the second stream reused the first window" - - -@pytest.mark.asyncio -async def test_an_extended_regime_wait_is_cut_short_by_stop(): - """Shutdown must not sit through an hour-long backoff. The healthy-stop case - is test_stop_closes_sse_and_finishes_task; this one stops mid-wait.""" - from ld_eventsource.errors import HTTPStatusError - - retry = _fast_retry_state(ONE_HOUR) - proc, store, ready, _ = _make_processor( - [_start(), _fault(error=HTTPStatusError(401))], retry_state=retry - ) - proc.start() - # Confirm the wait under test really is long before measuring the stop. - await _wait_until(lambda: retry.next_delay > 60) - - started = time.time() - await proc.stop() - elapsed = time.time() - started - - assert elapsed < 2, "stop() took %.2fs" % elapsed - leaked = [t for t in proc._runner._tasks if not t.done()] - assert leaked == [], "stop() returned with the task still running: %r" % leaked - - -@pytest.mark.asyncio -async def test_stop_before_start_and_stop_twice_are_safe(): - proc, store, ready, _ = _make_processor([]) - - await proc.stop() - await proc.stop() - - -@pytest.mark.asyncio -async def test_stop_closes_sse_and_finishes_task(): - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [_start(), _event('put', put_data)] - - proc, store, ready, factory = await _run_with_actions(actions) - assert ready.is_set() - - await proc.stop() - - # After stop() the SSE client is closed and no background task remains. - assert factory.created[0].closed - assert len(proc._runner._tasks) == 0 - - -@pytest.mark.asyncio -async def test_second_start_is_a_no_op(): - """AsyncLDClient.start() is documented as an idempotent no-op, so nothing - underneath it may raise on a repeat call.""" - actions = [_start()] - proc, store, ready, factory = _make_processor(actions) - proc.start() - try: - proc.start() - await _wait_until(lambda: len(factory.created) > 0) - assert len(factory.created) == 1 - finally: - await proc.stop() - - -@pytest.mark.asyncio -async def test_invalid_json_triggers_invalid_data_status(): - from ldclient.impl.datasource.async_status import ( - AsyncDataSourceUpdateSinkImpl - ) - from ldclient.impl.listeners import Listeners - - store = MockAsyncFeatureStore() - listeners = Listeners() - statuses = [] - listeners.add(lambda s: statuses.append(s)) - - config = _make_config() - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, listeners, Listeners()) - - # Deliver a put first so the processor initializes, then a bad patch. - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - bad_patch_data = 'not valid json' - actions = [ - _start(), - _event('put', put_data), - _event('patch', bad_patch_data), - ] - - proc, store, ready, _ = await _run_with_actions(actions, config=config, store=store) - await asyncio.sleep(0.1) # let patch event propagate - - error_statuses = [s for s in statuses if s.error is not None] - assert any( - s.error.kind == DataSourceErrorKind.INVALID_DATA for s in error_statuses - ), "Expected INVALID_DATA status from bad JSON" - - await proc.stop() - - -@pytest.mark.asyncio -async def test_patch_unknown_path_is_ignored(): - """A patch for an unknown path should log a warning and not crash.""" - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - bad_patch = json.dumps({"path": "/unknown/something", "data": {"key": "x", "version": 1}}) - actions = [_start(), _event('put', put_data), _event('patch', bad_patch)] - - proc, store, ready, _ = await _run_with_actions(actions) - await asyncio.sleep(0.05) - - # Store should be unchanged (still has f1 at version 1). - stored = await store.get(FEATURES, 'f1') - assert stored is not None - assert stored['version'] == 1 - - await proc.stop() - - -@pytest.mark.asyncio -async def test_initialized_reflects_store_state(): - proc, store, ready, _ = _make_processor([]) - assert not proc.initialized() - - proc.start() - # Seed the store and set ready manually to simulate post-put state. - flag = FlagBuilder('f1').version(1).build() - await store.init({FEATURES: {'f1': _item_dict(flag)}, SEGMENTS: {}}) - ready.set() - proc._running = True - - assert proc.initialized() - - await proc.stop() - - -class _FakeSession: - """Minimal stand-in for an aiohttp.ClientSession that records closure.""" - - def __init__(self): - self.closed = False - - async def close(self): - self.closed = True - - -@pytest.mark.asyncio -async def test_default_construction_builds_configured_session(): - """With no injected factory, a configured session is built (lazily, on the - event loop in _run) via make_client_session and handed to the SSE factory.""" - config = _make_config() - store = MockAsyncFeatureStore() - ready = asyncio.Event() - fake_session = _FakeSession() - - with mock.patch.object( - async_streaming, "make_client_session", return_value=fake_session - ) as make_session, mock.patch.object( - async_streaming, "AsyncSSEFactory" - ) as factory_cls: - factory_cls.return_value.create.return_value = _MockSSE([]) # empty stream -> _run blocks - proc = AsyncStreamingUpdateProcessor(with_async_update_sink(config, store), store, ready, None) - - # Deferred: nothing is created until the task runs. - assert proc._owned_session is None - - proc.start() - await _wait_until(lambda: proc._owned_session is not None) - - assert make_session.call_args == mock.call(config) - assert factory_cls.call_args.kwargs["session"] is fake_session - assert proc._owned_session is fake_session - - await proc.stop() - - -@pytest.mark.asyncio -async def test_default_construction_session_closed_on_stop(): - """The SDK-created session is closed when the processor stops.""" - config = _make_config() - store = MockAsyncFeatureStore() - ready = asyncio.Event() - fake_session = _FakeSession() - - with mock.patch.object( - async_streaming, "make_client_session", return_value=fake_session - ), mock.patch.object(async_streaming, "AsyncSSEFactory") as factory_cls: - factory_cls.return_value.create.return_value = _MockSSE([]) - proc = AsyncStreamingUpdateProcessor(with_async_update_sink(config, store), store, ready, None) - proc.start() - await _wait_until(lambda: proc._owned_session is not None) - - await proc.stop() - - assert fake_session.closed is True - assert proc._owned_session is None - - -@pytest.mark.asyncio -async def test_default_construction_session_closed_when_run_fails(): - """If _run fails after building the session (e.g. create() raises), the - SDK-created session is closed rather than leaked.""" - config = _make_config() - store = MockAsyncFeatureStore() - ready = asyncio.Event() - fake_session = _FakeSession() - - with mock.patch.object( - async_streaming, "make_client_session", return_value=fake_session - ), mock.patch.object(async_streaming, "AsyncSSEFactory") as factory_cls: - factory_cls.return_value.create.side_effect = RuntimeError("boom") - proc = AsyncStreamingUpdateProcessor(with_async_update_sink(config, store), store, ready, None) - proc.start() - - # _run builds the session, then create() raises. The finally must still - # close the SDK-created session instead of leaking it. - await _wait_until(lambda: fake_session.closed) - assert proc._owned_session is None - - -@pytest.mark.asyncio -async def test_injected_factory_leaves_session_unowned(): - """When a factory is injected, no session is built and none is owned.""" - with mock.patch.object(async_streaming, "make_client_session") as make_session: - proc, store, ready, factory = _make_processor([]) - proc.start() - await asyncio.sleep(0.02) # let _run start against the injected factory - - make_session.assert_not_called() - assert proc._owned_session is None - - # stop() must not attempt to close a session it doesn't own. - await proc.stop() - assert proc._owned_session is None - - -@pytest.mark.asyncio -async def test_diagnostics_recorded_on_successful_init(): - from ldclient.impl.events.diagnostics import _DiagnosticAccumulator - - diag = _DiagnosticAccumulator(1) - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - actions = [_start(), _event('put', put_data)] - - proc, store, ready, _ = await _run_with_actions(actions, diag=diag) - - recorded = diag.create_event_and_reset(0, 0)['streamInits'] - assert len(recorded) == 1 - assert recorded[0]['failed'] is False - - await proc.stop() - - -@pytest.mark.asyncio -async def test_off_is_reported_before_teardown(): - """A slow close must not hold back the status that tells a waiter to give - up, so OFF goes out before the connection and session are torn down.""" - order = [] - - class _OrderingSink: - async def init(self, all_data): - pass - - def update_status(self, new_state, new_error): - order.append(new_state) - - config = _make_config() - config._data_source_update_sink = _OrderingSink() - - flag = FlagBuilder('f1').version(1).build() - put_data = _make_put_data(flags={'f1': _item_dict(flag)}) - proc, _, _, factory = await _run_with_actions([_start(), _event('put', put_data)], config=config) - - sse = factory.created[0] - real_close = sse.close - - async def close(): - order.append('closed') - await real_close() - - sse.close = close - - await proc.stop() - - assert DataSourceState.OFF in order - assert order.index(DataSourceState.OFF) < order.index('closed') - - -def test_stream_init_duration_unaffected_by_wall_clock_step(monkeypatch): - processor = object.__new__(AsyncStreamingUpdateProcessor) - recorded = [] - - class _Recorder: - def record_stream_init(self, timestamp, duration, failed): - recorded.append((timestamp, duration, failed)) - - processor._diagnostic_accumulator = _Recorder() - processor._connection_attempt_started_monotonic = time.monotonic() - - real_time = time.time() - # A forward wall step between connect start and finish used to inflate the - # reported duration by the step size (a backward step was clamped to zero, - # silently losing the measurement). - monkeypatch.setattr(time, "time", lambda: real_time + 3600) - processor._record_stream_init(False) - - assert len(recorded) == 1 - _, duration, failed = recorded[0] - assert failed is False - assert duration >= 0 - assert duration < 1000 - - -def test_constructor_raises_without_update_sink(): - with pytest.raises(ValueError, match="data_source_update_sink"): - AsyncStreamingUpdateProcessor(_make_config(), MockAsyncFeatureStore(), asyncio.Event(), None) diff --git a/ldclient/testing/impl/datasource/test_feature_requester.py b/ldclient/testing/impl/datasource/test_feature_requester.py deleted file mode 100644 index badf566e..00000000 --- a/ldclient/testing/impl/datasource/test_feature_requester.py +++ /dev/null @@ -1,168 +0,0 @@ -from ldclient.config import Config -from ldclient.impl.datasource.feature_requester import FeatureRequesterImpl -from ldclient.testing.http_util import ( - BasicResponse, - JsonResponse, - start_server -) -from ldclient.testing.proxy_test_util import do_proxy_tests -from ldclient.version import VERSION -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - - -def test_get_all_data_returns_data(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri) - fr = FeatureRequesterImpl(config) - - flags = {'flag1': {'key': 'flag1'}} - segments = {'segment1': {'key': 'segment1'}} - resp_data = {'flags': flags, 'segments': segments} - expected_data = {FEATURES: flags, SEGMENTS: segments} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - result = fr.get_all_data() - assert result == expected_data - - -def test_get_all_data_with_headers_returns_response_headers(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri) - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data, {'X-LD-EnvID': 'env-abc-123'})) - - (data, headers) = fr.get_all_data_with_headers() - assert data == {FEATURES: {}, SEGMENTS: {}} - assert headers.get('X-LD-EnvID') == 'env-abc-123' - - -def test_get_all_data_sends_headers(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri) - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - fr.get_all_data() - req = server.require_request() - assert req.headers['Authorization'] == 'sdk-key' - assert req.headers['User-Agent'] == 'PythonClient/' + VERSION - assert req.headers['Accept-Encoding'] == 'gzip' - assert req.headers.get('X-LaunchDarkly-Wrapper') is None - assert req.headers.get('X-LaunchDarkly-Tags') is None - assert req.headers.get('X-LaunchDarkly-Instance-Id') is None - - -def test_sets_instance_id_header(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri) - config._instance_id = 'my-instance-id' - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - fr.get_all_data() - req = server.require_request() - assert req.headers.get('X-LaunchDarkly-Instance-Id') == 'my-instance-id' - - -def test_get_all_data_sends_wrapper_header(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri, wrapper_name='Flask', wrapper_version='0.1.0') - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - fr.get_all_data() - req = server.require_request() - assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask/0.1.0' - - -def test_get_all_data_sends_wrapper_header_without_version(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri, wrapper_name='Flask') - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - fr.get_all_data() - req = server.require_request() - assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask' - - -def test_get_all_data_sends_tags_header(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri, application={"id": "my-id", "version": "my-version"}) - fr = FeatureRequesterImpl(config) - - resp_data = {'flags': {}, 'segments': {}} - server.for_path('/sdk/latest-all', JsonResponse(resp_data)) - - fr.get_all_data() - req = server.require_request() - assert req.headers.get('X-LaunchDarkly-Tags') == 'application-id/my-id application-version/my-version' - - -def test_get_all_data_can_use_cached_data(): - with start_server() as server: - config = Config(sdk_key='sdk-key', base_uri=server.uri) - fr = FeatureRequesterImpl(config) - - etag1 = 'my-etag-1' - etag2 = 'my-etag-2' - resp_data1 = {'flags': {}, 'segments': {}} - resp_data2 = {'flags': {'flag1': {'key': 'flag1'}}, 'segments': {}} - expected_data1 = {FEATURES: {}, SEGMENTS: {}} - expected_data2 = {FEATURES: {'flag1': {'key': 'flag1'}}, SEGMENTS: {}} - req_path = '/sdk/latest-all' - server.for_path(req_path, JsonResponse(resp_data1, {'Etag': etag1})) - - result = fr.get_all_data() - assert result == expected_data1 - req = server.require_request() - assert 'If-None-Match' not in req.headers.keys() - - server.for_path(req_path, BasicResponse(304, None, {'Etag': etag1})) - - result = fr.get_all_data() - assert result == expected_data1 - req = server.require_request() - assert req.headers['If-None-Match'] == etag1 - - server.for_path(req_path, JsonResponse(resp_data2, {'Etag': etag2})) - - result = fr.get_all_data() - assert result == expected_data2 - req = server.require_request() - assert req.headers['If-None-Match'] == etag1 - - server.for_path(req_path, BasicResponse(304, None, {'Etag': etag2})) - - result = fr.get_all_data() - assert result == expected_data2 - req = server.require_request() - assert req.headers['If-None-Match'] == etag2 - - -def test_http_proxy(monkeypatch): - def _feature_requester_proxy_test(server, config, secure): - resp_data = {'flags': {}, 'segments': {}} - expected_data = {FEATURES: {}, SEGMENTS: {}} - server.for_path(config.base_uri + '/sdk/latest-all', JsonResponse(resp_data)) - fr = FeatureRequesterImpl(config) - if secure: - try: - fr.get_all_data() - except Exception: - pass # we expect this to fail because we don't have a real HTTPS proxy server - else: - result = fr.get_all_data() - assert result == expected_data - - do_proxy_tests(_feature_requester_proxy_test, 'GET', monkeypatch) diff --git a/ldclient/testing/impl/datasource/test_polling_processor.py b/ldclient/testing/impl/datasource/test_polling_processor.py deleted file mode 100644 index 9377f711..00000000 --- a/ldclient/testing/impl/datasource/test_polling_processor.py +++ /dev/null @@ -1,480 +0,0 @@ -import logging -import ssl -import threading -import time - -import mock -import pytest - -from ldclient.config import Config -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.datasource.polling import PollingUpdateProcessor -from ldclient.impl.datasource.status import DataSourceUpdateSinkImpl -from ldclient.impl.listeners import Listeners -from ldclient.impl.retry import ( - POLLING_RESET_SUCCESSES, - AfterConsecutiveSuccesses, - RetryState, - for_polling -) -from ldclient.impl.util import UnsuccessfulResponseException -from ldclient.interfaces import ( - DataSourceErrorKind, - DataSourceState, - DataSourceStatus -) -from ldclient.testing.builders import * -from ldclient.testing.mock_components import with_update_sink -from ldclient.testing.stub_util import MockFeatureRequester, MockResponse -from ldclient.testing.sync_util import wait_until -from ldclient.testing.test_util import SpyListener, no_retry_jitter -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -pp = None -mock_requester = None -store = None -ready = None - - -def setup_function(): - global mock_requester, store, ready - mock_requester = MockFeatureRequester() - store = InMemoryFeatureStore() - ready = threading.Event() - - -def teardown_function(): - if pp is not None: - pp.stop() - - -ONE_HOUR = 60 * 60 - - -def fast_retry_state(delay=0.05): - """A retry state whose every delay is ``delay``: small enough to skip the - real extended-regime wait, or large enough to prove a stop interrupts one.""" - return RetryState( - normal_initial_delay=delay, - normal_ceiling_delay=delay, - extended_initial_delay=delay, - extended_ceiling_delay=delay, - reset_policy=AfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES), - operating_cadence=delay, - ) - - -def setup_processor(config, retry_state=None): - global pp - pp = PollingUpdateProcessor(with_update_sink(config, store), mock_requester, store, ready, retry_state=retry_state) - pp.start() - - -def test_successful_request_puts_feature_data_in_store(): - flag = FlagBuilder('flagkey').build() - segment = SegmentBuilder('segkey').build() - mock_requester.all_data = {FEATURES: {"flagkey": flag.to_json_dict()}, SEGMENTS: {"segkey": segment.to_json_dict()}} - - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - setup_processor(config) - ready.wait() - assert store.get(FEATURES, "flagkey", lambda x: x) == flag - assert store.get(SEGMENTS, "segkey", lambda x: x) == segment - assert store.initialized - assert pp.initialized() - assert len(spy.statuses) == 1 - assert spy.statuses[0].state == DataSourceState.VALID - assert spy.statuses[0].error is None - - -# Note that we have to mock Config.poll_interval because Config won't let you set a value less than 30 seconds - - -@mock.patch('ldclient.config.Config.poll_interval', new_callable=mock.PropertyMock, return_value=0.1) -def test_general_connection_error_does_not_cause_immediate_failure(ignore_mock): - mock_requester.exception = Exception("bad") - setup_processor(Config("SDK_KEY")) - ready.wait(0.3) - assert not pp.initialized() - assert mock_requester.request_count >= 2 - - -def test_http_401_error_does_not_stop_polling(): - verify_unexpected_http_error(401) - - -def test_http_403_error_does_not_stop_polling(): - verify_unexpected_http_error(403) - - -def test_http_404_error_does_not_stop_polling(): - verify_unexpected_http_error(404) - - -def test_http_408_error_does_not_cause_immediate_failure(): - verify_recoverable_http_error(408) - - -def test_http_429_error_does_not_cause_immediate_failure(): - verify_recoverable_http_error(429) - - -def test_http_500_error_does_not_cause_immediate_failure(): - verify_recoverable_http_error(500) - - -def test_http_503_error_does_not_cause_immediate_failure(): - verify_recoverable_http_error(503) - - -@mock.patch('ldclient.config.Config.poll_interval', new_callable=mock.PropertyMock, return_value=0.1) -def verify_unexpected_http_error(http_status_code, ignore_mock): - """An error that needs a person to fix it -- a rejected SDK key, say -- is - still retried. It must not stop the poller, must not report OFF, and must - not falsely unblock initialization.""" - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - - mock_requester.exception = UnsuccessfulResponseException(http_status_code) - setup_processor(config, retry_state=fast_retry_state()) - finished = ready.wait(0.5) - assert not finished - assert not pp.initialized() - assert mock_requester.request_count >= 2 - - assert len(spy.statuses) > 1 - for status in spy.statuses: - assert status.state == DataSourceState.INITIALIZING - assert status.error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert status.error.status_code == http_status_code - - -@mock.patch('ldclient.config.Config.poll_interval', new_callable=mock.PropertyMock, return_value=0.1) -def test_unexpected_http_error_moves_to_the_extended_regime(ignore_mock): - retry = for_polling(0.1) - mock_requester.exception = UnsuccessfulResponseException(401) - setup_processor(Config("SDK_KEY"), retry_state=retry) - - # The extended regime starts at five minutes, so only the first poll runs. - wait_until(lambda: retry.next_delay > 0.1) - assert not ready.is_set() - assert mock_requester.request_count == 1 - - -def test_the_first_success_after_an_outage_polls_at_the_cadence(): - # A backoff wait applies to a retry, not to every operation. The retry - # state carries the wait, so this reads it there rather than measuring - # elapsed time. - with no_retry_jitter(): - retry = for_polling(30) - processor = PollingUpdateProcessor(with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=retry) - - mock_requester.exception = UnsuccessfulResponseException(401) - processor._poll() - assert retry.next_delay == 5 * 60 - - mock_requester.exception = None - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - processor._poll() - assert retry.next_delay == 30 - assert retry._extended, "one success restores the cadence but does not reset" - - processor._poll() - assert retry.next_delay == 30 - assert not retry._extended, "two successes in a row reset the state" - - -@pytest.mark.parametrize( - "error", - [ - ssl.SSLCertVerificationError("unable to get local issuer certificate"), - ssl.SSLEOFError("EOF occurred in violation of protocol"), - ConnectionResetError(104, "reset by peer"), - ], - ids=["certificate", "peer-close-handshake", "reset"], -) -def test_transport_failures_poll_again_at_the_cadence(error): - """No transport failure reaches the extended regime, a bad certificate - included. Only an HTTP status can do that.""" - retry = for_polling(30) - processor = PollingUpdateProcessor(with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=retry) - - mock_requester.exception = error - processor._poll() - assert retry.next_delay == 30 - assert not retry._extended - - -@mock.patch('ldclient.config.Config.poll_interval', new_callable=mock.PropertyMock, return_value=0.05) -def test_failure_transitions_from_valid(ignore_mock): - """A rejected SDK key after a poll has succeeded reports INTERRUPTED. OFF - is reserved for an explicit shutdown.""" - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - setup_processor(config, retry_state=fast_retry_state()) - assert ready.wait(2) - assert spy.statuses[0].state == DataSourceState.VALID - - mock_requester.exception = UnsuccessfulResponseException(401) - deadline = time.time() + 2 - while spy.statuses[-1].state == DataSourceState.VALID and time.time() < deadline: - time.sleep(0.01) - - assert spy.statuses[-1].state == DataSourceState.INTERRUPTED - assert spy.statuses[-1].error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert spy.statuses[-1].error.status_code == 401 - assert all(s.state != DataSourceState.OFF for s in spy.statuses) - - -def test_second_start_is_a_no_op(): - """A second start() must not raise. Thread.start() would, so the processor - guards it.""" - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - setup_processor(Config("SDK_KEY")) - pp.start() - - assert ready.wait(2) - assert pp.initialized() - - -def test_the_log_reports_the_growing_retry_delay(caplog): - """The message has to carry the real delay, so someone reading logs can see - the backoff working.""" - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_polling(30) - processor = PollingUpdateProcessor(with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=retry) - mock_requester.exception = UnsuccessfulResponseException(401) - processor._poll() - processor._poll() - - messages = [r.getMessage() for r in caplog.records] - assert messages == [ - "Received HTTP error 401 (invalid SDK key) for polling request - will retry in 300.0s", - "Received HTTP error 401 (invalid SDK key) for polling request - will retry in 600.0s", - ] - # An error a person has to fix is logged at error level, every time. - assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] - - -def test_a_normal_failure_logs_the_poll_interval_at_warning_level(caplog): - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_polling(30) - processor = PollingUpdateProcessor(with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=retry) - mock_requester.exception = UnsuccessfulResponseException(503) - processor._poll() - - record = caplog.records[0] - assert record.getMessage() == "Received HTTP error 503 for polling request - will retry in 30.0s" - assert record.levelno == logging.WARNING - - -def test_a_transport_error_reports_a_delay_and_keeps_its_stacktrace(caplog): - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_polling(30) - processor = PollingUpdateProcessor(with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=retry) - mock_requester.exception = ConnectionResetError(104, "reset by peer") - processor._poll() - - record = caplog.records[0] - assert record.getMessage() == "Error encountered when updating flags: [Errno 104] reset by peer - will retry in 30.0s" - # The handler has exited by the time this is logged, so the exception has to - # be carried explicitly for the traceback to survive. - assert record.exc_info is not None - - -def _polling_thread(): - """Finds the task's worker thread by name, so a test can prove it exited - without reaching into the task's private state.""" - return next((t for t in threading.enumerate() if t.name == "ldclient.datasource.polling.repeating"), None) - - -def test_an_extended_regime_wait_is_cut_short_by_stop(): - """The reason the wait has to be interruptible at all. A 401 puts the next - poll five minutes out, and shutdown must not sit through it.""" - mock_requester.exception = UnsuccessfulResponseException(401) - retry = for_polling(30) - setup_processor(Config("SDK_KEY"), retry_state=retry) - - # Let the first poll happen, so the task is inside the long wait. - deadline = time.time() + 2 - while mock_requester.request_count < 1 and time.time() < deadline: - time.sleep(0.01) - assert mock_requester.request_count == 1 - assert retry._extended, "the wait under test should be minutes long" - - worker = _polling_thread() - assert worker is not None - - started = time.time() - pp.stop() - worker.join(2) - elapsed = time.time() - started - - # Without an interruptible wait this join would time out and the thread - # would still be sitting in a 300-second sleep. - assert not worker.is_alive() - assert elapsed < 1 - - -def test_an_absurd_poll_interval_does_not_kill_the_worker_thread(): - """``Event.wait`` raises above ``threading.TIMEOUT_MAX``, and that raise is - outside the try block around the poll, so the thread used to die while the - SDK still reported itself healthy.""" - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - setup_processor(Config("SDK_KEY", poll_interval=1e10)) - - assert ready.wait(2) - worker = _polling_thread() - assert worker is not None - - # A thread that raised on the wait exits as soon as the first poll returns. - worker.join(0.3) - assert worker.is_alive() - - -def test_stop_twice_and_stop_before_start_are_safe(): - """Neither a stop before the first poll nor a second stop should raise, - including while an hour-long wait is pending.""" - mock_requester.exception = UnsuccessfulResponseException(401) - processor = PollingUpdateProcessor( - with_update_sink(Config("SDK_KEY"), store), mock_requester, store, ready, retry_state=fast_retry_state(ONE_HOUR) - ) - - processor.stop() - processor.stop() - processor.start() - processor.stop() - - -def test_stop_reports_off(): - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - setup_processor(config) - assert ready.wait(2) - - pp.stop() - - assert spy.statuses[-1].state == DataSourceState.OFF - - -def test_a_poll_finishing_after_stop_reports_nothing(): - """The poll still in flight when stop() ran must not report after OFF.""" - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - processor = PollingUpdateProcessor(with_update_sink(config, store), mock_requester, store, ready) - - processor.stop() - processor._poll() - - assert [status.state for status in spy.statuses] == [DataSourceState.OFF] - - -def test_valid_status_is_reported_before_ready_is_set(): - # Mirrors go-server-sdk#442: a caller that wakes on readiness must not - # still be able to read INITIALIZING. - observed = [] - listeners = Listeners() - listeners.add(lambda status: observed.append((status.state, ready.is_set()))) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - setup_processor(config) - assert ready.wait(2) - - assert observed[0] == (DataSourceState.VALID, False) - - -@mock.patch('ldclient.config.Config.poll_interval', new_callable=mock.PropertyMock, return_value=0.1) -def verify_recoverable_http_error(http_status_code, ignore_mock): - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - - mock_requester.exception = UnsuccessfulResponseException(http_status_code) - setup_processor(config) - finished = ready.wait(0.5) - assert not finished - assert not pp.initialized() - assert mock_requester.request_count >= 2 - - assert len(spy.statuses) > 1 - - for status in spy.statuses: - assert status.state == DataSourceState.INITIALIZING - assert status.error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert status.error.status_code == http_status_code - - -class MockFeatureRequesterWithHeaders(MockFeatureRequester): - def __init__(self, headers): - super().__init__() - self.headers = headers - - def get_all_data_with_headers(self): - return (self.get_all_data(), self.headers) - - -def test_records_environment_id_from_polling_headers(): - global mock_requester - mock_requester = MockFeatureRequesterWithHeaders({'X-LD-EnvID': 'env-abc-123'}) - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - - config = Config("SDK_KEY") - sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - config._data_source_update_sink = sink - setup_processor(config) - assert ready.wait(2) - - assert sink.environment_id == 'env-abc-123' - - -def test_environment_id_is_none_when_requester_provides_no_headers(): - mock_requester.all_data = {FEATURES: {}, SEGMENTS: {}} - - config = Config("SDK_KEY") - sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - config._data_source_update_sink = sink - setup_processor(config) - assert ready.wait(2) - - assert sink.environment_id is None - - -def test_constructor_raises_without_update_sink(): - with pytest.raises(ValueError, match="data_source_update_sink"): - PollingUpdateProcessor(Config("SDK_KEY"), mock_requester, store, ready) diff --git a/ldclient/testing/impl/datasource/test_streaming.py b/ldclient/testing/impl/datasource/test_streaming.py deleted file mode 100644 index c153e356..00000000 --- a/ldclient/testing/impl/datasource/test_streaming.py +++ /dev/null @@ -1,1044 +0,0 @@ -import logging -import ssl -import time -from threading import Event, Thread -from typing import List - -import pytest -from ld_eventsource import SSEClient -from ld_eventsource.actions import Fault -from ld_eventsource.config import ( - ConnectStrategy, - ErrorStrategy, - RetryDelayStrategy -) -from ld_eventsource.errors import HTTPStatusError - -from ldclient.config import Config -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.datasource.datasource_common import StreamClosedError -from ldclient.impl.datasource.status import DataSourceUpdateSinkImpl -from ldclient.impl.datasource.streaming import StreamingUpdateProcessor -from ldclient.impl.events.diagnostics import _DiagnosticAccumulator -from ldclient.impl.listeners import Listeners -from ldclient.impl.retry import ( - NORMAL_STREAMING_CEILING_DELAY, - STREAMING_RESET_INTERVAL, - AfterHealthyFor, - RetryState, - for_streaming -) -from ldclient.interfaces import ( - DataSourceErrorKind, - DataSourceState, - DataSourceStatus -) -from ldclient.testing.builders import * -from ldclient.testing.http_util import ( - BasicResponse, - CauseNetworkError, - SequentialHandler, - start_server -) -from ldclient.testing.mock_components import with_update_sink -from ldclient.testing.proxy_test_util import do_proxy_tests -from ldclient.testing.stub_util import ( - make_delete_event, - make_invalid_put_event, - make_patch_event, - make_put_event, - stream_content -) -from ldclient.testing.sync_util import wait_until -from ldclient.testing.test_util import ( - SpyListener, - no_retry_jitter, - record_healthy_windows, - ticking_clock -) -from ldclient.version import VERSION -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -brief_delay = 0.001 -ONE_HOUR = 60 * 60 - - -def fast_retry_state(delay=brief_delay): - """A retry state whose every delay is ``delay``: small enough to skip the - real extended-regime wait, or large enough to prove a stop interrupts one.""" - return RetryState( - normal_initial_delay=delay, - normal_ceiling_delay=delay, - extended_initial_delay=delay, - extended_ceiling_delay=delay, - reset_policy=AfterHealthyFor(STREAMING_RESET_INTERVAL), - ) - - -# These long timeouts are necessary because of a problem in the Windows CI environment where HTTP requests to -# the test server running at localhost tests are *extremely* slow. It looks like a similar issue to what's -# described at https://stackoverflow.com/questions/2617615/slow-python-http-server-on-localhost but we had no -# luck with the advice that was given there. -start_wait = 10 -update_wait = 3 - - -def test_request_properties(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - req = server.await_request() - assert req.method == 'GET' - assert req.headers.get('Authorization') == 'sdk-key' - assert req.headers.get('User-Agent') == 'PythonClient/' + VERSION - assert req.headers.get('X-LaunchDarkly-Wrapper') is None - assert req.headers.get('X-LaunchDarkly-Instance-Id') is None - assert req.headers.get('X-LaunchDarkly-Tags') is None - - -def test_sends_instance_id(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, wrapper_name='Flask', wrapper_version='0.1.0') - config._instance_id = 'my-instance-id' - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - req = server.await_request() - assert req.headers.get('X-LaunchDarkly-Instance-Id') == 'my-instance-id' - - -def test_sends_wrapper_header(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, wrapper_name='Flask', wrapper_version='0.1.0') - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - req = server.await_request() - assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask/0.1.0' - - -def test_sends_wrapper_header_without_version(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, wrapper_name='Flask') - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - req = server.await_request() - assert req.headers.get('X-LaunchDarkly-Wrapper') == 'Flask' - - -def test_sends_tag_header(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, application={"id": "my-id", "version": "my-version"}) - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - req = server.await_request() - assert req.headers.get('X-LaunchDarkly-Tags') == 'application-id/my-id application-version/my-version' - - -def test_receives_put_event(): - store = InMemoryFeatureStore() - ready = Event() - flag = FlagBuilder('flagkey').version(1).build() - segment = SegmentBuilder('segkey').version(1).build() - - with start_server() as server: - with stream_content(make_put_event([flag], [segment])) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - expect_item(store, FEATURES, flag) - expect_item(store, SEGMENTS, segment) - - -def test_receives_patch_events(): - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - flagv2 = FlagBuilder('flagkey').version(2).build() - segmentv1 = SegmentBuilder('segkey').version(1).build() - segmentv2 = SegmentBuilder('segkey').version(2).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1], [segmentv1])) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - expect_item(store, FEATURES, flagv1) - expect_item(store, SEGMENTS, segmentv1) - - stream.push(make_patch_event(FEATURES, flagv2)) - expect_update(store, FEATURES, flagv2) - - stream.push(make_patch_event(SEGMENTS, segmentv2)) - expect_update(store, SEGMENTS, segmentv2) - - -def test_receives_delete_events(): - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - segmentv1 = SegmentBuilder('segkey').version(1).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1], [segmentv1])) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - expect_item(store, FEATURES, flagv1) - expect_item(store, SEGMENTS, segmentv1) - - stream.push(make_delete_event(FEATURES, flagv1['key'], 2)) - expect_delete(store, FEATURES, flagv1['key']) - - stream.push(make_delete_event(SEGMENTS, segmentv1['key'], 2)) - expect_delete(store, SEGMENTS, segmentv1['key']) - - -def test_reconnects_if_stream_is_broken(): - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - flagv2 = FlagBuilder('flagkey').version(2).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1])) as stream1: - with stream_content(make_put_event([flagv2])) as stream2: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', SequentialHandler(stream1, stream2)) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - server.await_request - ready.wait(start_wait) - assert sp.initialized() - expect_item(store, FEATURES, flagv1) - - stream1.close() - server.await_request - expect_update(store, FEATURES, flagv2) - - -def test_retries_on_network_error(): - error_handler = CauseNetworkError() - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - two_errors_then_success = SequentialHandler(error_handler, error_handler, stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', two_errors_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.await_request - server.await_request - - -@pytest.mark.parametrize("status", [400, 408, 429, 500, 503]) -def test_recoverable_http_error(status): - error_handler = BasicResponse(status) - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - two_errors_then_success = SequentialHandler(error_handler, error_handler, stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', two_errors_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.should_have_requests(3) - - -@pytest.mark.parametrize("status", [401, 403, 404]) -def test_unexpected_http_error_backs_off_a_long_way(status): - """An error that needs a person to fix it does not stop the stream, but the - next attempt is five minutes out, so only one request is made here.""" - error_handler = BasicResponse(status) - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - error_then_success = SequentialHandler(error_handler, stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', error_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - server.wait_until_request_received() - # The next attempt is past the normal ceiling, so the failure - # has been recorded and the extended regime is in use. - wait_until(lambda: sp._retry.next_delay > NORMAL_STREAMING_CEILING_DELAY) - - # Initialization is not falsely unblocked. - assert not ready.is_set() - assert not sp.initialized() - assert sp.is_alive() - server.should_have_requests(1) - - -@pytest.mark.parametrize("status", [401, 403, 404]) -def test_unexpected_http_error_keeps_retrying(status): - """The same failure with the delay compressed: the stream recovers once the - service does, rather than staying down for ever.""" - error_handler = BasicResponse(status) - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - error_then_success = SequentialHandler(error_handler, stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - server.for_path('/all', error_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=fast_retry_state()) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.should_have_requests(2) - - assert all(s.state != DataSourceState.OFF for s in spy.statuses) - assert spy.statuses[0].state == DataSourceState.INITIALIZING - assert spy.statuses[0].error.status_code == status - assert spy.statuses[-1].state == DataSourceState.VALID - - -def test_sse_client_hands_us_the_fault_before_it_waits(): - """Pins the ld_eventsource ordering the SDK relies on. - - The SDK computes and takes the retry delay itself, which only works - because SSEClient yields the Fault to the caller before its next connect - attempt sleeps. A library change that slept first would make this test - time out rather than fail quietly. - """ - with start_server() as server: - server.for_path('/all', BasicResponse(503)) - client = SSEClient( - connect=ConnectStrategy.http(url=server.uri + '/all'), - error_strategy=ErrorStrategy.always_continue(), - initial_retry_delay=30, - retry_delay_strategy=RetryDelayStrategy.default(max_delay=30, backoff_multiplier=2), - retry_delay_reset_threshold=0, - ) - try: - started = time.time() - first = next(iter(client.all)) - elapsed = time.time() - started - finally: - client.close() - - assert isinstance(first, Fault) - assert isinstance(first.error, HTTPStatusError) - # The library has a long delay queued up but has not taken it yet. - assert client.next_retry_delay >= 15 - assert elapsed < 5 - - -def test_the_sdk_configures_the_sse_client_never_to_wait(): - """The SDK owns the delay, so the library's own delay must stay at zero - however long the outage lasts.""" - store = InMemoryFeatureStore() - with start_server() as server: - server.for_path('/all', BasicResponse(503)) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=30) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None) - client = sp._create_sse_client() - try: - actions = iter(client.all) - first = next(actions) - second = next(actions) - finally: - client.close() - - assert isinstance(first, Fault) - assert isinstance(second, Fault) - assert client.next_retry_delay == 0 - - -def test_server_close_backs_off_and_keeps_the_stream_running(): - """The service normally leaves the connection open, so a clean close is a - connection failure: the SDK reports it and backs off, rather than - reconnecting in a tight loop.""" - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - flagv2 = FlagBuilder('flagkey').version(2).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1])) as stream1: - with stream_content(make_put_event([flagv2])) as stream2: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - server.for_path('/all', SequentialHandler(stream1, stream2)) - - retry = fast_retry_state() - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=retry) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - - stream1.close() - expect_update(store, FEATURES, flagv2) - - assert retry._attempts >= 1 - assert not retry._extended - - interrupted = [s for s in spy.statuses if s.state == DataSourceState.INTERRUPTED] - assert len(interrupted) >= 1 - assert interrupted[0].error.kind == DataSourceErrorKind.NETWORK_ERROR - - -def test_server_close_uses_the_normal_delay_curve(): - """A clean close is a NORMAL failure. Classifying it UNEXPECTED would put - a routine load-balancer drain into the extended regime and take a fleet - out of service for up to an hour.""" - store = InMemoryFeatureStore() - config = Config(sdk_key='sdk-key', initial_reconnect_delay=1) - retry = for_streaming(1) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None, retry_state=retry) - sp._running = True - sp._stop_event.set() # so the wait returns at once - - delays = [] - for _ in range(8): - sp._handle_error(StreamClosedError()) - delays.append(retry._max_delay) - - assert not retry._extended - assert delays == [30] * 8 - - -def test_our_own_interrupt_is_not_counted_as_a_server_close(): - """Bad JSON makes the SDK drop the connection itself. The SSE client then - reports that close as a Fault with no error, and counting it would record - the same failure twice and wait twice.""" - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as valid_stream, stream_content(make_invalid_put_event()) as invalid_stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - statuses: List[DataSourceStatus] = [] - listeners = Listeners() - - # The stream fixture holds the connection open, so it has to be - # closed for the server to move on to the next handler. This - # mirrors test_invalid_json_triggers_listener. - def listener(s): - if len(statuses) == 0: - invalid_stream.close() - statuses.append(s) - - listeners.add(listener) - - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - server.for_path('/all', SequentialHandler(invalid_stream, valid_stream)) - - retry = fast_retry_state() - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=retry) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.should_have_requests(2) - - # One failure for the bad JSON, not a second for the close it - # caused. - assert retry._attempts == 1 - - -def test_a_leaked_interrupt_flag_does_not_swallow_a_server_close(): - """interrupt() is a no-op when the connection has already gone, so no - Fault arrives to clear the flag. A new connection must clear it, or the - next genuine close is recorded as ours and the backoff is skipped.""" - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - flagv2 = FlagBuilder('flagkey').version(2).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1])) as stream1: - with stream_content(make_put_event([flagv2])) as stream2: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', SequentialHandler(stream1, stream2)) - - retry = fast_retry_state() - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=retry) as sp: - sp._interrupted_by_sdk = True - sp.start() - ready.wait(start_wait) - assert sp.initialized() - - stream1.close() - expect_update(store, FEATURES, flagv2) - - assert retry._attempts == 1 - - -def test_stop_before_start_does_not_raise(): - """stop() can land before run() has built the SSE client.""" - config = Config(sdk_key='sdk-key', stream_uri='http://localhost') - sp = StreamingUpdateProcessor(with_update_sink(config, InMemoryFeatureStore()), InMemoryFeatureStore(), Event(), None) - sp.stop() - - -def test_a_stop_before_the_connection_exists_still_ends_the_run(): - """stop() has nothing to close when run() has not built the client yet, so - the run itself must not go on to read a connection nobody will close.""" - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - server.for_path('/all', stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) - - sp.stop() - thread = Thread(target=sp.run, daemon=True) - thread.start() - thread.join(update_wait) - - assert not thread.is_alive() - assert not ready.is_set() - assert not store.initialized - - -def test_a_raise_inside_the_loop_closes_the_connection(): - """A raise the loop does not catch must not leak the connection pool.""" - store = InMemoryFeatureStore() - closes: List[int] = [] - - with start_server() as server: - with stream_content(make_put_event()) as stream: - server.for_path('/all', stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None) - - # KeyboardInterrupt is not an Exception, so the loop cannot catch it. - def explode(*args, **kwargs): - raise KeyboardInterrupt() - - sp._process_message = explode # type: ignore[method-assign] - - real_create = sp._create_sse_client - - def create_and_watch_close(): - client = real_create() - real_close = client.close - - def close(): - closes.append(1) - real_close() - - client.close = close # type: ignore[method-assign] - return client - - sp._create_sse_client = create_and_watch_close # type: ignore[method-assign] - - with pytest.raises(KeyboardInterrupt): - sp.run() - - assert closes == [1] - - -def _handle_errors_without_waiting(retry, errors): - """Drives _handle_error for each error and returns nothing. The stop event - is pre-set so the interruptible wait returns at once.""" - store = InMemoryFeatureStore() - config = Config(sdk_key='sdk-key', initial_reconnect_delay=1) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None, retry_state=retry) - sp._running = True - sp._stop_event.set() - for error in errors: - sp._handle_error(error) - - -def test_the_log_reports_the_growing_retry_delay(caplog): - """The message has to carry the real delay, so someone reading logs can see - the backoff working. The vaguer wording it replaced could not show this.""" - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_streaming(1) - _handle_errors_without_waiting(retry, [HTTPStatusError(401), HTTPStatusError(401)]) - - messages = [r.getMessage() for r in caplog.records] - assert messages == [ - "Received HTTP error 401 (invalid SDK key) for stream connection - will retry in 300.0s", - "Received HTTP error 401 (invalid SDK key) for stream connection - will retry in 600.0s", - ] - # An error a person has to fix is logged at error level, every time. - assert [r.levelno for r in caplog.records] == [logging.ERROR, logging.ERROR] - - -def test_a_normal_failure_logs_a_short_delay_at_warning_level(caplog): - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_streaming(1) - _handle_errors_without_waiting(retry, [HTTPStatusError(503), HTTPStatusError(503)]) - - messages = [r.getMessage() for r in caplog.records] - assert messages == [ - "Received HTTP error 503 for stream connection - will retry in 1.0s", - "Received HTTP error 503 for stream connection - will retry in 2.0s", - ] - assert [r.levelno for r in caplog.records] == [logging.WARNING, logging.WARNING] - - -def test_a_server_close_and_a_transport_error_both_report_a_delay(caplog): - caplog.set_level(logging.WARNING) - - with no_retry_jitter(): - retry = for_streaming(1) - _handle_errors_without_waiting(retry, [StreamClosedError(), ConnectionResetError(104, "reset by peer")]) - - messages = [r.getMessage() for r in caplog.records] - assert messages[0] == "The server closed the stream connection - will retry in 1.0s" - assert messages[1] == "Error on stream connection: [Errno 104] reset by peer - will retry in 2.0s" - - -def test_an_extended_regime_wait_is_cut_short_by_stop(): - """The reason the wait has to be interruptible at all. Shutdown must not - sit through an hour-long backoff.""" - store = InMemoryFeatureStore() - with start_server() as server: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', BasicResponse(401)) - retry = fast_retry_state(ONE_HOUR) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None, retry_state=retry) as sp: - sp.start() - server.wait_until_request_received() - # Confirm the wait under test really is long before measuring the stop. - wait_until(lambda: retry.next_delay > 60) - - started = time.time() - sp.stop() - sp.join(5) - elapsed = time.time() - started - - assert not sp.is_alive() - assert elapsed < 2, "stop() took %.2fs" % elapsed - - -def test_several_messages_on_one_stream_do_not_extend_the_reset_window(): - """The window starts at the first message and stays there, however many - more arrive on the same stream.""" - store = InMemoryFeatureStore() - ready = Event() - flag = FlagBuilder('flagkey').version(1).build() - - with start_server() as server: - with stream_content(make_put_event([flag]) + make_patch_event(FEATURES, flag)) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', stream) - - policy = AfterHealthyFor(STREAMING_RESET_INTERVAL) - retry = RetryState( - normal_initial_delay=brief_delay, - normal_ceiling_delay=brief_delay, - extended_initial_delay=brief_delay, - extended_ceiling_delay=brief_delay, - reset_policy=policy, - ) - # The clock moves on every read, so a window that had been - # restarted reads back as a different time. - windows = record_healthy_windows(policy) - with ticking_clock(): - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=retry) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - expect_update(store, FEATURES, flag) - - assert len(windows) >= 2, "both messages should have signalled" - assert len(set(windows)) == 1, "the window moved between messages" - - -def test_a_fresh_stream_starts_a_new_reset_window(): - """A stream teardown clears the window through record_failure, so the next - stream measures its own stretch rather than inheriting the old one.""" - store = InMemoryFeatureStore() - ready = Event() - flagv1 = FlagBuilder('flagkey').version(1).build() - flagv2 = FlagBuilder('flagkey').version(2).build() - - with start_server() as server: - with stream_content(make_put_event([flagv1])) as stream1: - with stream_content(make_put_event([flagv2])) as stream2: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', SequentialHandler(stream1, stream2)) - - policy = AfterHealthyFor(STREAMING_RESET_INTERVAL) - retry = RetryState( - normal_initial_delay=brief_delay, - normal_ceiling_delay=brief_delay, - extended_initial_delay=brief_delay, - extended_ceiling_delay=brief_delay, - reset_policy=policy, - ) - windows = record_healthy_windows(policy) - with ticking_clock(): - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None, retry_state=retry) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - - stream1.close() - expect_update(store, FEATURES, flagv2) - - assert len(set(windows)) == 2, "the second stream reused the first window" - - -@pytest.mark.parametrize( - "error", - [ - ssl.SSLCertVerificationError("unable to get local issuer certificate"), - ssl.SSLEOFError("EOF occurred in violation of protocol"), - ConnectionResetError(104, "reset by peer"), - ], - ids=["certificate", "peer-close-handshake", "reset"], -) -def test_transport_failures_stay_in_the_normal_regime(error): - """No transport failure reaches the extended regime, a bad certificate - included. Only an HTTP status can do that.""" - store = InMemoryFeatureStore() - config = Config(sdk_key='sdk-key', initial_reconnect_delay=1) - retry = for_streaming(1) - sp = StreamingUpdateProcessor(with_update_sink(config, store), store, Event(), None, retry_state=retry) - sp._running = True - sp._stop_event.set() # so the wait returns at once - - sp._handle_error(error) - - assert not retry._extended - assert retry._max_delay == 30 - - -def test_http_proxy(monkeypatch): - def _stream_processor_proxy_test(server, config, secure): - store = InMemoryFeatureStore() - ready = Event() - with stream_content(make_put_event()) as stream: - server.for_path(config.stream_base_uri + '/all', stream) - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - # Wait till the server has received a request. We need to do this even though do_proxy_tests also - # does it, because if we return too soon out of this block, the object returned by stream_content - # could be closed and the test server would no longer work. - server.wait_until_request_received() - if not secure: - # We only do this part with HTTP, because with HTTPS we don't have a real enough proxy server - # for the stream connection to work correctly - we can only detect the request. - ready.wait(start_wait) - assert sp.initialized() - - do_proxy_tests(_stream_processor_proxy_test, 'GET', monkeypatch) - - -def test_records_diagnostic_on_stream_init_success(): - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - server.for_path('/all', stream) - diag_accum = _DiagnosticAccumulator(1) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, diag_accum) as sp: - sp.start() - ready.wait(start_wait) - recorded_inits = diag_accum.create_event_and_reset(0, 0)['streamInits'] - - assert len(recorded_inits) == 1 - assert recorded_inits[0]['failed'] is False - - -def test_records_diagnostic_on_stream_init_failure(): - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - error_then_success = SequentialHandler(BasicResponse(503), stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - server.for_path('/all', error_then_success) - diag_accum = _DiagnosticAccumulator(1) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, diag_accum) as sp: - sp.start() - ready.wait(start_wait) - recorded_inits = diag_accum.create_event_and_reset(0, 0)['streamInits'] - - assert len(recorded_inits) == 2 - assert recorded_inits[0]['failed'] is True - assert recorded_inits[1]['failed'] is False - - -@pytest.mark.parametrize("status", [400, 408, 429, 500, 503]) -def test_status_includes_http_code(status): - error_handler = BasicResponse(status) - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as stream: - two_errors_then_success = SequentialHandler(error_handler, error_handler, stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - server.for_path('/all', two_errors_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.should_have_requests(3) - - assert len(spy.statuses) == 3 - - assert spy.statuses[0].state == DataSourceState.INITIALIZING - assert spy.statuses[0].error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert spy.statuses[0].error.status_code == status - - assert spy.statuses[1].state == DataSourceState.INITIALIZING - assert spy.statuses[1].error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert spy.statuses[1].error.status_code == status - - assert spy.statuses[2].state == DataSourceState.VALID - assert spy.statuses[2].error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert spy.statuses[2].error.status_code == status - - -def test_invalid_json_triggers_listener(): - store = InMemoryFeatureStore() - ready = Event() - with start_server() as server: - with stream_content(make_put_event()) as valid_stream, stream_content(make_invalid_put_event()) as invalid_stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - statuses: List[DataSourceStatus] = [] - listeners = Listeners() - - def listener(s): - if len(statuses) == 0: - invalid_stream.close() - statuses.append(s) - - listeners.add(listener) - - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - server.for_path('/all', SequentialHandler(invalid_stream, valid_stream)) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sp.initialized() - server.should_have_requests(2) - - assert len(statuses) == 2 - - assert statuses[0].state == DataSourceState.INITIALIZING - assert statuses[0].error.kind == DataSourceErrorKind.INVALID_DATA - assert statuses[0].error.status_code == 0 - - assert statuses[1].state == DataSourceState.VALID - - -def test_failure_transitions_from_valid(): - """A rejected SDK key after the stream was valid reports INTERRUPTED. OFF - is reserved for an explicit shutdown.""" - store = InMemoryFeatureStore() - ready = Event() - error_handler = BasicResponse(401) - with start_server() as server: - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - - # The sink has special handling for failures before the state is valid. So we manually set this to valid so we - # can exercise the other branching logic within the sink. - config.data_source_update_sink.update_status(DataSourceState.VALID, None) - server.for_path('/all', error_handler) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - server.wait_until_request_received() - wait_until(lambda: len(spy.statuses) == 2) - - # The 401 is retried five minutes out, so readiness never fires. - assert not ready.is_set() - server.should_have_requests(1) - - assert len(spy.statuses) == 2 - - assert spy.statuses[0].state == DataSourceState.VALID - - assert spy.statuses[1].state == DataSourceState.INTERRUPTED - assert spy.statuses[1].error.kind == DataSourceErrorKind.ERROR_RESPONSE - assert spy.statuses[1].error.status_code == 401 - - -def test_records_environment_id_from_stream_headers(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event(), headers={'X-LD-EnvID': 'env-abc-123'}) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - config._data_source_update_sink = sink - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sink.environment_id == 'env-abc-123' - - -def test_environment_id_is_none_when_not_provided(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - config = Config(sdk_key='sdk-key', stream_uri=server.uri) - sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - config._data_source_update_sink = sink - server.for_path('/all', stream) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sink.environment_id is None - - -def test_does_not_record_environment_id_from_error_response_headers(): - store = InMemoryFeatureStore() - ready = Event() - - with start_server() as server: - with stream_content(make_put_event()) as stream: - error_then_success = SequentialHandler(BasicResponse(503, None, {'X-LD-EnvID': 'env-from-error'}), stream) - config = Config(sdk_key='sdk-key', stream_uri=server.uri, initial_reconnect_delay=brief_delay) - sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - config._data_source_update_sink = sink - server.for_path('/all', error_then_success) - - with StreamingUpdateProcessor(with_update_sink(config, store), store, ready, None) as sp: - sp.start() - ready.wait(start_wait) - assert sink.environment_id is None - - -def expect_item(store, kind, item): - assert store.get(kind, item['key'], lambda x: x) == item - - -def expect_update(store, kind, expected_item): - await_item(store, kind, expected_item['key'], expected_item) - - -def expect_delete(store, kind, key): - await_item(store, kind, key, None) - - -def await_item(store, kind, key, expected_item): - deadline = time.time() + update_wait - while time.time() < deadline: - time.sleep(0.05) - current_item = store.get(kind, key, lambda x: x) - if current_item == expected_item: - return - assert False, 'expected %s = %s but value was still %s after %d seconds' % (key, json.dumps(expected_item), json.dumps(current_item), update_wait) - - -def test_stream_init_duration_unaffected_by_wall_clock_step(monkeypatch): - processor = object.__new__(StreamingUpdateProcessor) - recorded = [] - - class _Recorder: - def record_stream_init(self, timestamp, duration, failed): - recorded.append((timestamp, duration, failed)) - - processor._diagnostic_accumulator = _Recorder() - processor._connection_attempt_started_monotonic = time.monotonic() - - real_time = time.time() - # A forward wall step between connect start and finish used to inflate the - # reported duration by the step size (a backward step was clamped to zero, - # silently losing the measurement). - monkeypatch.setattr(time, "time", lambda: real_time + 3600) - processor._record_stream_init(False) - - assert len(recorded) == 1 - _, duration, failed = recorded[0] - assert failed is False - assert duration >= 0 - assert duration < 1000 - - -def test_constructor_raises_without_update_sink(): - with pytest.raises(ValueError, match="data_source_update_sink"): - StreamingUpdateProcessor(Config("SDK_KEY"), InMemoryFeatureStore(), Event(), None) diff --git a/ldclient/testing/impl/datasourcev2/test_payload_filter.py b/ldclient/testing/impl/datasourcev2/test_request_query.py similarity index 81% rename from ldclient/testing/impl/datasourcev2/test_payload_filter.py rename to ldclient/testing/impl/datasourcev2/test_request_query.py index 471f02c7..46fadf6c 100644 --- a/ldclient/testing/impl/datasourcev2/test_payload_filter.py +++ b/ldclient/testing/impl/datasourcev2/test_request_query.py @@ -1,7 +1,6 @@ """ -The FDv2 data system does not support payload filtering. These tests show that its data sources do -not send the payload filter key, also when the config has one. This includes the FDv1 fallback -requesters, so that a fallback does not change the client to a filtered subset of the data. +The FDv2 data sources send no query parameters except the basis. The FDv1 fallback requesters send +none. In particular, no data source sends a payload filter. """ from unittest import mock @@ -23,7 +22,6 @@ from ldclient.testing.http_util import start_server from ldclient.testing.mock_components import MockSelectorStore -FILTER_KEY = 'microservice-1' SELECTOR = Selector.new_selector('p:SOMETHING:300', 300) @@ -33,14 +31,14 @@ def path_and_query(request): def make_config(base_uri: str = 'http://localhost') -> Config: - return Config('sdk-key', base_uri=base_uri, stream_uri=base_uri, payload_filter_key=FILTER_KEY) + return Config('sdk-key', base_uri=base_uri, stream_uri=base_uri) @pytest.mark.parametrize('selector, expected_query', [ (None, {}), (SELECTOR, {'basis': [SELECTOR.state]}), ]) -def test_polling_requester_does_not_send_the_filter(selector, expected_query): +def test_polling_requester_sends_only_the_basis(selector, expected_query): with start_server() as server: config = make_config(server.uri) requester = Urllib3PollingRequester(config, config.base_uri, config.http) @@ -48,7 +46,7 @@ def test_polling_requester_does_not_send_the_filter(selector, expected_query): assert path_and_query(server.require_request()) == ('/sdk/poll', expected_query) -def test_fdv1_fallback_polling_requester_does_not_send_the_filter(): +def test_fdv1_fallback_polling_requester_sends_only_the_basis(): with start_server() as server: config = make_config(server.uri) requester = Urllib3FDv1PollingRequester(config, config.base_uri, config.http) @@ -61,7 +59,7 @@ def test_fdv1_fallback_polling_requester_does_not_send_the_filter(): (None, {}), (SELECTOR, {'basis': [SELECTOR.state]}), ]) -async def test_async_polling_requester_does_not_send_the_filter(selector, expected_query): +async def test_async_polling_requester_sends_only_the_basis(selector, expected_query): with start_server() as server: config = make_config(server.uri) requester = AiohttpPollingRequester(config, config.base_uri, config.http) @@ -73,7 +71,7 @@ async def test_async_polling_requester_does_not_send_the_filter(selector, expect @pytest.mark.asyncio -async def test_async_fdv1_fallback_polling_requester_does_not_send_the_filter(): +async def test_async_fdv1_fallback_polling_requester_sends_only_the_basis(): with start_server() as server: config = make_config(server.uri) requester = AiohttpFDv1PollingRequester(config, config.base_uri, config.http) @@ -88,7 +86,7 @@ async def test_async_fdv1_fallback_polling_requester_does_not_send_the_filter(): (Selector.no_selector(), {}), (SELECTOR, {'basis': SELECTOR.state}), ]) -def test_streaming_does_not_send_the_filter(selector, expected_params): +def test_streaming_sends_only_the_basis(selector, expected_params): config = make_config() with mock.patch.object(streaming.ConnectStrategy, 'http', wraps=streaming.ConnectStrategy.http) as http: streaming.create_sse_client(config.stream_base_uri, config.http, config.initial_reconnect_delay, config, MockSelectorStore(selector)) @@ -102,7 +100,7 @@ def test_streaming_does_not_send_the_filter(selector, expected_params): (Selector.no_selector(), {}), (SELECTOR, {'basis': SELECTOR.state}), ]) -def test_async_streaming_does_not_send_the_filter(selector, expected_params): +def test_async_streaming_sends_only_the_basis(selector, expected_params): config = make_config() with mock.patch.object(async_streaming, 'AsyncSSEFactory') as factory_cls: async_streaming.create_sse_client( diff --git a/ldclient/testing/impl/datasystem/test_async_fdv2.py b/ldclient/testing/impl/datasystem/test_async_fdv2.py index ff6e05ca..3966c588 100644 --- a/ldclient/testing/impl/datasystem/test_async_fdv2.py +++ b/ldclient/testing/impl/datasystem/test_async_fdv2.py @@ -1,7 +1,6 @@ # pylint: disable=missing-docstring import asyncio -import logging from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional import pytest @@ -752,17 +751,3 @@ async def test_successful_ops_pass_through(): assert got is not None and got["key"] == "flag-a" allf = await wrapper.all(FEATURES) assert "flag-a" in allf - - -def test_warns_when_payload_filter_key_is_configured(caplog): - caplog.set_level(logging.WARNING, logger="ldclient.util") - AsyncFDv2(AsyncConfig(sdk_key="dummy", payload_filter_key="microservice-1"), DataSystemConfig(initializers=None, synchronizers=None)) - - assert any("Payload filtering is not supported with the FDv2 data system" in record.message for record in caplog.records) - - -def test_does_not_warn_when_payload_filter_key_is_not_configured(caplog): - caplog.set_level(logging.WARNING, logger="ldclient.util") - AsyncFDv2(AsyncConfig(sdk_key="dummy"), DataSystemConfig(initializers=None, synchronizers=None)) - - assert not any("Payload filtering" in record.message for record in caplog.records) diff --git a/ldclient/testing/impl/datasystem/test_async_store_view.py b/ldclient/testing/impl/datasystem/test_async_store_view.py index c348f003..d71beb32 100644 --- a/ldclient/testing/impl/datasystem/test_async_store_view.py +++ b/ldclient/testing/impl/datasystem/test_async_store_view.py @@ -4,7 +4,7 @@ import pytest -from ldclient.impl.datasystem.async_fdv1 import _AsyncReadOnlyFeatureStoreView +from ldclient.impl.datasystem.async_fdv2 import _AsyncReadOnlyStoreView from ldclient.versioned_data_kind import FEATURES, VersionedDataKind @@ -31,10 +31,24 @@ async def all(self, kind: VersionedDataKind) -> Dict[str, Any]: return dict(self._data) +class FakeDataSystemStore: + """Data system store shape: reads go to the active store.""" + + def __init__(self, active: FakeAsyncStore): + self._active = active + + def get_active_store(self) -> FakeAsyncStore: + return self._active + + +def _view(data: Dict[str, Any]) -> _AsyncReadOnlyStoreView: + return _AsyncReadOnlyStoreView(FakeDataSystemStore(FakeAsyncStore(data))) # type: ignore[arg-type] + + @pytest.mark.asyncio -async def test_async_feature_store_view_get_decodes_dict(): +async def test_async_store_view_get_decodes_dict(): raw = _flag_dict("flag-a", 1) - view = _AsyncReadOnlyFeatureStoreView(FakeAsyncStore({"flag-a": raw})) + view = _view({"flag-a": raw}) result = await view.get(FEATURES, "flag-a") @@ -43,9 +57,9 @@ async def test_async_feature_store_view_get_decodes_dict(): @pytest.mark.asyncio -async def test_async_feature_store_view_get_passes_through_model(): +async def test_async_store_view_get_passes_through_model(): decoded = FEATURES.decode(_flag_dict("flag-a", 1)) - view = _AsyncReadOnlyFeatureStoreView(FakeAsyncStore({"flag-a": decoded})) + view = _view({"flag-a": decoded}) result = await view.get(FEATURES, "flag-a") @@ -53,16 +67,16 @@ async def test_async_feature_store_view_get_passes_through_model(): @pytest.mark.asyncio -async def test_async_feature_store_view_get_missing_returns_none(): - view = _AsyncReadOnlyFeatureStoreView(FakeAsyncStore({})) +async def test_async_store_view_get_missing_returns_none(): + view = _view({}) assert await view.get(FEATURES, "missing") is None @pytest.mark.asyncio -async def test_async_feature_store_view_all_decodes_each_value(): +async def test_async_store_view_all_decodes_each_value(): raw_a = _flag_dict("flag-a", 1) decoded_b = FEATURES.decode(_flag_dict("flag-b", 1)) - view = _AsyncReadOnlyFeatureStoreView(FakeAsyncStore({"flag-a": raw_a, "flag-b": decoded_b})) + view = _view({"flag-a": raw_a, "flag-b": decoded_b}) result = await view.all(FEATURES) diff --git a/ldclient/testing/impl/datasystem/test_fdv1_stop.py b/ldclient/testing/impl/datasystem/test_fdv1_stop.py deleted file mode 100644 index 2962bfe1..00000000 --- a/ldclient/testing/impl/datasystem/test_fdv1_stop.py +++ /dev/null @@ -1,71 +0,0 @@ -# pylint: disable=missing-docstring - -from threading import Event - -import pytest - -from ldclient.async_config import AsyncConfig -from ldclient.async_feature_store import AsyncInMemoryFeatureStore -from ldclient.config import Config -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.aio.concurrency import AsyncEvent -from ldclient.impl.datasystem.async_fdv1 import AsyncFDv1 -from ldclient.impl.datasystem.fdv1 import FDv1 - - -class _ClosingStore(InMemoryFeatureStore): - def __init__(self): - super().__init__() - self.close_count = 0 - - def close(self) -> None: - self.close_count += 1 - - -class _AsyncClosingStore(AsyncInMemoryFeatureStore): - def __init__(self): - super().__init__() - self.close_count = 0 - - async def close(self) -> None: - self.close_count += 1 - - -def test_stop_closes_the_feature_store(): - store = _ClosingStore() - data_system = FDv1(Config(sdk_key="key", offline=True, feature_store=store)) - data_system.start(Event()) - - data_system.stop() - - assert store.close_count == 1 - - -def test_stop_closes_the_feature_store_when_not_started(): - store = _ClosingStore() - data_system = FDv1(Config(sdk_key="key", offline=True, feature_store=store)) - - data_system.stop() - - assert store.close_count == 1 - - -@pytest.mark.asyncio -async def test_async_stop_closes_the_feature_store(): - store = _AsyncClosingStore() - data_system = AsyncFDv1(AsyncConfig(sdk_key="key", offline=True), store, lambda: None) - data_system.start(AsyncEvent()) - - await data_system.stop() - - assert store.close_count == 1 - - -@pytest.mark.asyncio -async def test_async_stop_closes_the_feature_store_when_not_started(): - store = _AsyncClosingStore() - data_system = AsyncFDv1(AsyncConfig(sdk_key="key", offline=True), store, lambda: None) - - await data_system.stop() - - assert store.close_count == 1 diff --git a/ldclient/testing/impl/datasystem/test_fdv2_datasystem.py b/ldclient/testing/impl/datasystem/test_fdv2_datasystem.py index 6cc98a85..d4699e32 100644 --- a/ldclient/testing/impl/datasystem/test_fdv2_datasystem.py +++ b/ldclient/testing/impl/datasystem/test_fdv2_datasystem.py @@ -1,6 +1,5 @@ # pylint: disable=missing-docstring -import logging import os import tempfile from threading import Event @@ -847,17 +846,3 @@ def test_environment_id_is_not_recorded_from_non_valid_updates(): assert fdv2.environment_id == "env-from-sync" fdv2.stop() - - -def test_warns_when_payload_filter_key_is_configured(caplog): - caplog.set_level(logging.WARNING, logger="ldclient.util") - FDv2(Config(sdk_key="dummy", payload_filter_key="microservice-1"), DataSystemConfig(initializers=None, synchronizers=None)) - - assert any("Payload filtering is not supported with the FDv2 data system" in record.message for record in caplog.records) - - -def test_does_not_warn_when_payload_filter_key_is_not_configured(caplog): - caplog.set_level(logging.WARNING, logger="ldclient.util") - FDv2(Config(sdk_key="dummy"), DataSystemConfig(initializers=None, synchronizers=None)) - - assert not any("Payload filtering" in record.message for record in caplog.records) diff --git a/ldclient/testing/test_feature_store_client_wrapper.py b/ldclient/testing/impl/datasystem/test_fdv2_store_client_wrapper.py similarity index 88% rename from ldclient/testing/test_feature_store_client_wrapper.py rename to ldclient/testing/impl/datasystem/test_fdv2_store_client_wrapper.py index ed744378..6875dafc 100644 --- a/ldclient/testing/test_feature_store_client_wrapper.py +++ b/ldclient/testing/impl/datasystem/test_fdv2_store_client_wrapper.py @@ -2,8 +2,8 @@ from typing import Callable, List from unittest.mock import Mock -from ldclient.impl.datastore.status import DataStoreUpdateSinkImpl -from ldclient.impl.datasystem.fdv1 import _FeatureStoreClientWrapper +from ldclient.impl.datasystem.fdv2 import _FeatureStoreClientWrapper +from ldclient.impl.datasystem.fdv2_common import DataStoreStatusProviderImpl from ldclient.impl.listeners import Listeners from ldclient.versioned_data_kind import FEATURES @@ -40,7 +40,7 @@ def test_store_will_not_notify_if_wrapped_store_does_not_support_monitoring(): listener = RecordStatusListener() listeners = Listeners() listeners.add(listener) - sink = DataStoreUpdateSinkImpl(listeners) + sink = DataStoreStatusProviderImpl(store, listeners) wrapper = _FeatureStoreClientWrapper(store, sink) try: @@ -56,11 +56,12 @@ def test_store_will_not_notify_if_wrapped_store_cannot_come_back_online(): store = Mock() store.is_monitoring_enabled = lambda: True store.init = raise_an_error + store.is_available = lambda: False listener = RecordStatusListener() listeners = Listeners() listeners.add(listener) - sink = DataStoreUpdateSinkImpl(listeners) + sink = DataStoreStatusProviderImpl(store, listeners) wrapper = _FeatureStoreClientWrapper(store, sink) try: @@ -90,7 +91,7 @@ def set_event(status): listener = CallbackListener(set_event) listeners = Listeners() listeners.add(listener) - sink = DataStoreUpdateSinkImpl(listeners) + sink = DataStoreStatusProviderImpl(store, listeners) wrapper = _FeatureStoreClientWrapper(store, sink) try: @@ -113,7 +114,7 @@ def test_writes_after_close_do_not_reach_the_store(): listener = RecordStatusListener() listeners = Listeners() listeners.add(listener) - sink = DataStoreUpdateSinkImpl(listeners) + sink = DataStoreStatusProviderImpl(store, listeners) wrapper = _FeatureStoreClientWrapper(store, sink) wrapper.close() @@ -145,7 +146,7 @@ def slow_upsert(kind, item): store.upsert = slow_upsert store.close = lambda: calls.append('close') - wrapper = _FeatureStoreClientWrapper(store, DataStoreUpdateSinkImpl(Listeners())) + wrapper = _FeatureStoreClientWrapper(store, DataStoreStatusProviderImpl(store, Listeners())) writer = Thread(target=lambda: wrapper.upsert(FEATURES, {'key': 'flag', 'version': 1})) writer.start() @@ -179,7 +180,7 @@ def close_on_failure(status): listeners = Listeners() listeners.add(CallbackListener(close_on_failure)) - wrapper = _FeatureStoreClientWrapper(store, DataStoreUpdateSinkImpl(listeners)) + wrapper = _FeatureStoreClientWrapper(store, DataStoreStatusProviderImpl(store, listeners)) writer = Thread(target=lambda: _ignore_errors(lambda: wrapper.init({})), daemon=True) writer.start() diff --git a/ldclient/testing/impl/datasystem/test_store_view.py b/ldclient/testing/impl/datasystem/test_store_view.py index 6dfec9be..a35622c3 100644 --- a/ldclient/testing/impl/datasystem/test_store_view.py +++ b/ldclient/testing/impl/datasystem/test_store_view.py @@ -2,7 +2,6 @@ from typing import Any, Callable, Dict -from ldclient.impl.datasystem.fdv1 import _ReadOnlyFeatureStoreView from ldclient.impl.datasystem.fdv2 import _ReadOnlyStoreView from ldclient.impl.datasystem.store import Store from ldclient.impl.listeners import Listeners @@ -52,43 +51,13 @@ def initialized(self) -> bool: return True -def test_feature_store_view_get_decodes_dict_and_passes_callback(): - raw = _flag_dict("flag-a", 1) - view = _ReadOnlyFeatureStoreView(FakeSyncFeatureStore({"flag-a": raw})) # type: ignore[arg-type] - - result = view.get(FEATURES, "flag-a") - assert result == FEATURES.decode(raw) - assert not isinstance(result, dict) - - key = view.get(FEATURES, "flag-a", lambda flag: flag.key if flag else None) - assert key == "flag-a" - - -def test_feature_store_view_get_passes_through_model(): +def test_store_view_passes_through_a_model_from_the_persistent_store(): decoded = FEATURES.decode(_flag_dict("flag-a", 1)) - view = _ReadOnlyFeatureStoreView(FakeSyncFeatureStore({"flag-a": decoded})) # type: ignore[arg-type] - assert view.get(FEATURES, "flag-a") is decoded - - -def test_feature_store_view_get_missing_returns_none(): - view = _ReadOnlyFeatureStoreView(FakeSyncFeatureStore({})) # type: ignore[arg-type] - assert view.get(FEATURES, "missing") is None - - -def test_feature_store_view_all_decodes_and_passes_callback(): - raw = _flag_dict("flag-a", 1) - view = _ReadOnlyFeatureStoreView(FakeSyncFeatureStore({"flag-a": raw})) # type: ignore[arg-type] - - result = view.all(FEATURES) - assert result["flag-a"] == FEATURES.decode(raw) - - count = view.all(FEATURES, lambda items: len(items)) - assert count == 1 - + store = Store(Listeners(), Listeners()) + store.with_persistence(FakeSyncFeatureStore({"flag-a": decoded}), False, None) # type: ignore[arg-type] + view = _ReadOnlyStoreView(store) -def test_feature_store_view_initialized_delegates(): - view = _ReadOnlyFeatureStoreView(FakeSyncFeatureStore({})) # type: ignore[arg-type] - assert view.initialized is True + assert view.get(FEATURES, "flag-a") is decoded def test_store_view_get_decodes_and_passes_callback(): diff --git a/ldclient/testing/impl/events/test_diagnostics.py b/ldclient/testing/impl/events/test_diagnostics.py index cb3722f7..32f2325a 100644 --- a/ldclient/testing/impl/events/test_diagnostics.py +++ b/ldclient/testing/impl/events/test_diagnostics.py @@ -1,6 +1,7 @@ import json import uuid +from ldclient import datasystem from ldclient.config import Config, HTTPConfig from ldclient.feature_store import CacheConfig from ldclient.feature_store_helpers import CachingStoreWrapper @@ -50,7 +51,7 @@ def test_create_diagnostic_config_defaults(): test_config = Config("SDK_KEY") diag_config = _create_diagnostic_config_object(test_config) - assert len(diag_config) == 16 + assert len(diag_config) == 14 assert diag_config['customBaseURI'] is False assert diag_config['customEventsURI'] is False assert diag_config['customStreamURI'] is False @@ -59,8 +60,6 @@ def test_create_diagnostic_config_defaults(): assert diag_config['socketTimeoutMillis'] == 15000 assert diag_config['eventsFlushIntervalMillis'] == 5000 assert diag_config['usingProxy'] is False - assert diag_config['streamingDisabled'] is False - assert diag_config['usingRelayDaemon'] is False assert diag_config['allAttributesPrivate'] is False assert diag_config['pollingIntervalMillis'] == 30000 assert diag_config['userKeysCapacity'] == 1000 @@ -78,10 +77,8 @@ def test_create_diagnostic_config_custom(): events_max_pending=10, flush_interval=1, stream_uri='https://test.com', - stream=False, poll_interval=60, - use_ldd=True, - feature_store=test_store, + datasystem_config=datasystem.daemon(test_store).build(), all_attributes_private=True, context_keys_capacity=10, context_keys_flush_interval=60, @@ -90,7 +87,7 @@ def test_create_diagnostic_config_custom(): ) diag_config = _create_diagnostic_config_object(test_config) - assert len(diag_config) == 16 + assert len(diag_config) == 14 assert diag_config['customBaseURI'] is True assert diag_config['customEventsURI'] is True assert diag_config['customStreamURI'] is True @@ -99,8 +96,6 @@ def test_create_diagnostic_config_custom(): assert diag_config['socketTimeoutMillis'] == 1000 assert diag_config['eventsFlushIntervalMillis'] == 1000 assert diag_config['usingProxy'] is True - assert diag_config['streamingDisabled'] is True - assert diag_config['usingRelayDaemon'] is True assert diag_config['allAttributesPrivate'] is True assert diag_config['pollingIntervalMillis'] == 60000 assert diag_config['userKeysCapacity'] == 10 diff --git a/ldclient/testing/impl/test_data_sink.py b/ldclient/testing/impl/test_data_sink.py deleted file mode 100644 index 9c901860..00000000 --- a/ldclient/testing/impl/test_data_sink.py +++ /dev/null @@ -1,382 +0,0 @@ -import time -from typing import Callable, Dict - -import mock -import pytest - -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.datasource.status import DataSourceUpdateSinkImpl -from ldclient.impl.listeners import Listeners -from ldclient.interfaces import ( - DataSourceErrorInfo, - DataSourceErrorKind, - DataSourceState -) -from ldclient.testing.builders import ( - FlagBuilder, - FlagRuleBuilder, - SegmentBuilder, - SegmentRuleBuilder, - make_clause -) -from ldclient.testing.test_util import SpyListener -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - - -@pytest.fixture -def basic_data() -> Dict: - flag1 = FlagBuilder('flag1').version(1).on(False).build() - flag2 = FlagBuilder('flag2').version(1).on(False).build() - flag3 = ( - FlagBuilder('flag3').version(1).rules(FlagRuleBuilder().variation(0).id('rule_id').track_events(True).clauses(make_clause('user', 'segmentMatch', 'segmentMatch', 'segment2')).build()).build() - ) - segment1 = SegmentBuilder('segment1').version(1).build() - segment2 = SegmentBuilder('segment2').version(1).build() - - return { - FEATURES: { - flag1.key: flag1.to_json_dict(), - flag2.key: flag2.to_json_dict(), - flag3.key: flag3.to_json_dict(), - }, - SEGMENTS: { - segment1.key: segment1.to_json_dict(), - segment2.key: segment2.to_json_dict(), - }, - } - - -@pytest.fixture -def prereq_data() -> Dict: - flag1 = FlagBuilder('flag1').version(1).on(False).prerequisite('flag2', 0).build() - flag2 = FlagBuilder('flag2').version(1).on(False).prerequisite('flag3', 0).prerequisite('flag4', 0).prerequisite('flag6', 0).build() - flag3 = FlagBuilder('flag3').version(1).on(False).build() - flag4 = FlagBuilder('flag4').version(1).on(False).build() - flag5 = FlagBuilder('flag5').version(1).on(False).build() - flag6 = ( - FlagBuilder('flag6').version(1).rules(FlagRuleBuilder().variation(0).id('rule_id').track_events(True).clauses(make_clause('user', 'segmentMatch', 'segmentMatch', 'segment2')).build()).build() - ) - segment1 = SegmentBuilder('segment1').version(1).build() - segment2 = SegmentBuilder('segment2').version(1).rules(SegmentRuleBuilder().clauses(make_clause('user', 'segmentMatch', 'segmentMatch', 'segment1')).build()).build() - - return { - FEATURES: { - flag1.key: flag1.to_json_dict(), - flag2.key: flag2.to_json_dict(), - flag3.key: flag3.to_json_dict(), - flag4.key: flag4.to_json_dict(), - flag5.key: flag5.to_json_dict(), - flag6.key: flag6.to_json_dict(), - }, - SEGMENTS: { - segment1.key: segment1.to_json_dict(), - segment2.key: segment2.to_json_dict(), - }, - } - - -def test_defaults_to_initializing(): - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), Listeners()) - assert sink.status.state == DataSourceState.INITIALIZING - - -def test_interrupting_initializing_stays_initializing(): - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), Listeners()) - sink.update_status(DataSourceState.INTERRUPTED, None) - assert sink.status.state == DataSourceState.INITIALIZING - assert sink.status.error is None - - -def test_off_is_terminal(): - spy = SpyListener() - status_listener = Listeners() - status_listener.add(spy) - - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), status_listener, Listeners()) - sink.update_status(DataSourceState.VALID, None) - sink.update_status(DataSourceState.OFF, None) - - # A poll or stream connection still in flight when the data source stopped. - # Test both a plain state change and one carrying an error, so neither can - # get through. - sink.update_status(DataSourceState.VALID, None) - sink.update_status(DataSourceState.INTERRUPTED, DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, time.time(), 'late')) - - assert sink.status.state == DataSourceState.OFF - assert sink.status.error is None - assert [status.state for status in spy.statuses] == [DataSourceState.VALID, DataSourceState.OFF] - - -@mock.patch('ldclient.feature_store.InMemoryFeatureStore.init', side_effect=[Exception('cannot init')]) -def test_store_error_after_off_reports_nothing(mock_init, prereq_data): - spy = SpyListener() - status_listener = Listeners() - status_listener.add(spy) - - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), status_listener, Listeners()) - sink.update_status(DataSourceState.OFF, None) - - with pytest.raises(Exception): - sink.init(prereq_data) - - assert sink.status.state == DataSourceState.OFF - assert [status.state for status in spy.statuses] == [DataSourceState.OFF] - - -def test_listener_is_only_triggered_for_state_changes(): - spy = SpyListener() - status_listener = Listeners() - status_listener.add(spy) - - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), status_listener, Listeners()) - sink.update_status(DataSourceState.VALID, None) - sink.update_status(DataSourceState.VALID, None) - assert len(spy.statuses) == 1 - - sink.update_status(DataSourceState.INTERRUPTED, None) - sink.update_status(DataSourceState.INTERRUPTED, None) - assert len(spy.statuses) == 2 - - -def test_all_listeners_triggered_for_single_change(): - spy1 = SpyListener() - spy2 = SpyListener() - - status_listener = Listeners() - status_listener.add(spy1) - status_listener.add(spy2) - - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), status_listener, Listeners()) - sink.update_status(DataSourceState.VALID, None) - - assert len(spy1.statuses) == 1 - assert len(spy2.statuses) == 1 - - -def test_is_called_once_per_flag_during_init(basic_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(basic_data) - - flag1 = FlagBuilder('flag1').version(2).on(False).build() - flag4 = FlagBuilder('flag4').version(1).on(False).build() - - spy = SpyListener() - flag_change_listener.add(spy) - sink.init( - { - FEATURES: { - flag1.key: flag1, - flag4.key: flag4, - } - } - ) - - assert len(spy.statuses) == 4 - keys = set(s.key for s in spy.statuses) # No guaranteed order - - assert 'flag1' in keys # Version update - assert 'flag2' in keys # Deleted - assert 'flag3' in keys # Deleted - assert 'flag4' in keys # Newly created - - -def test_upsert_triggers_flag_listener(basic_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(basic_data) - - spy = SpyListener() - flag_change_listener.add(spy) - sink.upsert(FEATURES, FlagBuilder('flag1').version(2).on(False).build()) - - assert len(spy.statuses) == 1 - assert spy.statuses[0].key == 'flag1' - - -def test_rejected_upsert_does_not_trigger_flag_listener(basic_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(basic_data) - - spy = SpyListener() - flag_change_listener.add(spy) - # The store already has version 1 of this flag, so it rejects this write. - sink.upsert(FEATURES, FlagBuilder('flag1').version(1).on(False).build()) - - assert len(spy.statuses) == 0 - - -def test_delete_triggers_flag_listener(basic_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(basic_data) - - spy = SpyListener() - flag_change_listener.add(spy) - sink.delete(FEATURES, 'flag1', 2) - # The store rejects this duplicate delete, so it sends no change event. - sink.delete(FEATURES, 'flag1', 2) - - assert len(spy.statuses) == 1 - assert spy.statuses[0].key == 'flag1' - - -def test_triggers_if_segment_changes(basic_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(basic_data) - - spy = SpyListener() - flag_change_listener.add(spy) - sink.upsert(SEGMENTS, SegmentBuilder('segment2').version(2).build()) - - assert len(spy.statuses) == 1 - assert spy.statuses[0].key == 'flag3' - - -def test_dependency_stack_if_top_of_chain_is_changed(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.upsert(FEATURES, FlagBuilder('flag4').version(2).on(False).build()) - - assert len(spy.statuses) == 3 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - assert 'flag4' in keys - - -def test_triggers_when_new_prereqs_added(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.upsert(FEATURES, FlagBuilder('flag3').version(2).on(False).prerequisite('flag4', 0).build()) - - assert len(spy.statuses) == 3 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - assert 'flag3' in keys - - -def test_triggers_when_prereqs_removed(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.upsert(FEATURES, FlagBuilder('flag2').version(2).on(False).prerequisite('flag3', 0).build()) - - assert len(spy.statuses) == 2 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - - -def test_triggers_dependency_stack_if_top_of_chain_is_deleted(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.delete(FEATURES, 'flag4', 2) - - assert len(spy.statuses) == 3 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - assert 'flag4' in keys - - -def test_triggers_dependent_segment_is_modified(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.upsert(SEGMENTS, SegmentBuilder('segment1').version(2).build()) - # The store rejects this duplicate upsert, so it sends no change events. - sink.upsert(SEGMENTS, SegmentBuilder('segment1').version(2).build()) - - assert len(spy.statuses) == 3 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - assert 'flag6' in keys - - -def test_triggers_if_dependent_segment_removed(prereq_data): - flag_change_listener = Listeners() - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), Listeners(), flag_change_listener) - sink.init(prereq_data) - - spy = SpyListener() - flag_change_listener.add(spy) - - sink.delete(SEGMENTS, 'segment2', 2) - # The store rejects this duplicate delete, so it sends no change events. - sink.delete(SEGMENTS, 'segment2', 2) - - assert len(spy.statuses) == 3 - - keys = set(s.key for s in spy.statuses) - assert 'flag1' in keys - assert 'flag2' in keys - assert 'flag6' in keys - - -def confirm_store_error(fn: Callable[[DataSourceUpdateSinkImpl], None], expected_error: str): - status_listeners = Listeners() - - sink = DataSourceUpdateSinkImpl(InMemoryFeatureStore(), status_listeners, Listeners()) - # Make it valid first so the error changes from initializing - sink.update_status(DataSourceState.VALID, None) - - spy = SpyListener() - status_listeners.add(spy) - - try: - fn(sink) - except (Exception,): - pass - - assert len(spy.statuses) == 1 - assert spy.statuses[0].state == DataSourceState.INTERRUPTED - assert spy.statuses[0].error.kind == DataSourceErrorKind.STORE_ERROR - assert spy.statuses[0].error.message == expected_error - - -@mock.patch('ldclient.feature_store.InMemoryFeatureStore.init', side_effect=[Exception('cannot init')]) -def test_listener_is_triggered_for_init_error(prereq_data): - confirm_store_error(lambda sink: sink.init(prereq_data), 'cannot init') - - -@mock.patch('ldclient.feature_store.InMemoryFeatureStore.upsert', side_effect=[Exception('cannot upsert')]) -def test_listener_is_triggered_for_upsert_error(prereq_data): - confirm_store_error(lambda sink: sink.upsert(FEATURES, {}), 'cannot upsert') - - -@mock.patch('ldclient.feature_store.InMemoryFeatureStore.delete', side_effect=[Exception('cannot delete')]) -def test_listener_is_triggered_for_delete_error(prereq_data): - confirm_store_error(lambda sink: sink.delete(FEATURES, 'key', 1), 'cannot delete') diff --git a/ldclient/testing/impl/test_retry.py b/ldclient/testing/impl/test_retry.py deleted file mode 100644 index 138f5182..00000000 --- a/ldclient/testing/impl/test_retry.py +++ /dev/null @@ -1,571 +0,0 @@ -""" -Tests for ldclient.impl.retry. - -Nothing here sleeps. A test that needs to move time on uses ``frozen_clock``, -which replaces the ``time`` module the retry module reads. Jitter is removed -for every test by an autouse fixture, so a delay assertion reads the -undisturbed value; the tests that are about jitter override it. -""" - -import logging -import math -import random -from contextlib import contextmanager -from unittest import mock - -import pytest - -from ldclient.config import ( - DEFAULT_INITIAL_RECONNECT_DELAY, - DEFAULT_POLL_INTERVAL -) -from ldclient.impl import retry -from ldclient.impl.retry import ( - EXTENDED_CEILING_DELAY, - EXTENDED_INITIAL_DELAY, - NORMAL_STREAMING_CEILING_DELAY, - POLLING_RESET_SUCCESSES, - STREAMING_RESET_INTERVAL, - AfterConsecutiveSuccesses, - AfterHealthyFor, - FailureKind, - RetryState, - classify_http_status, - for_polling, - for_streaming -) -from ldclient.testing.test_util import fixed_retry_jitter, no_retry_jitter - -NORMAL = FailureKind.NORMAL -UNEXPECTED = FailureKind.UNEXPECTED - - -class _FrozenClock: - """Stands in for the ``time`` module. Time only moves when a test says so.""" - - def __init__(self, now: float): - self.now = now - - def monotonic(self) -> float: - return self.now - - def advance(self, seconds: float) -> None: - self.now += seconds - - -@contextmanager -def frozen_clock(now: float = 1000.0): - """Freezes the clock the retry module reads. - - Patching the module's own ``time`` reference keeps the change local to - ``ldclient.impl.retry``; every other module keeps the real clock. - """ - clock = _FrozenClock(now) - with mock.patch.object(retry, 'time', clock): - yield clock - - -# The random draw just below 1, which subtracts the most jitter possible: -# half the delay. -FULL_JITTER = 0.9999999 - - -@pytest.fixture(autouse=True) -def without_jitter(): - """Removes jitter for every test in this module, so a delay assertion can - read the undisturbed value.""" - with no_retry_jitter(): - yield - - -@contextmanager -def real_jitter(): - """Restores the real random source, for a test that asserts the bounds hold - for any draw rather than for one fixed value.""" - with mock.patch.object(retry, 'random', random): - yield - - -def failure_delay(state, kind=NORMAL) -> float: - """Records a failure and reads back the wait it decided, which is the value - a data source reads.""" - state.record_failure(kind) - return state.next_delay - - -class TestClassifyHttpStatus: - @pytest.mark.parametrize("status", [400, 408, 429]) - def test_retryable_4xx_statuses_are_normal(self, status): - assert classify_http_status(status) is NORMAL - - @pytest.mark.parametrize("status", [401, 403, 404, 405, 418, 499]) - def test_other_4xx_statuses_are_unexpected(self, status): - assert classify_http_status(status) is UNEXPECTED - - @pytest.mark.parametrize("status", [500, 502, 503, 504, 599]) - def test_5xx_statuses_are_normal(self, status): - assert classify_http_status(status) is NORMAL - - @pytest.mark.parametrize("status", [200, 204, 301, 399]) - def test_non_error_statuses_are_normal(self, status): - assert classify_http_status(status) is NORMAL - - -class TestFactoryInputGuards: - """``Config`` reports these options as configured, so the factories are the - only guard. A non-positive value would retry with no wait; a non-finite one - makes the jitter arithmetic produce NaN.""" - - @pytest.mark.parametrize( - "configured", - [0, -1, -0.5, float('inf'), float('-inf'), float('nan')], - ids=["zero", "negative", "negative-fraction", "inf", "-inf", "nan"], - ) - def test_streaming_falls_back_to_the_default(self, configured, caplog): - caplog.set_level(logging.WARNING) - - state = for_streaming(configured) - delay = failure_delay(state, NORMAL) - - assert state._min_delay == DEFAULT_INITIAL_RECONNECT_DELAY - assert delay == DEFAULT_INITIAL_RECONNECT_DELAY - assert math.isfinite(delay) and delay > 0 - assert caplog.records[0].getMessage() == ( - "initial_reconnect_delay must be a positive, finite number of seconds; using the default of 1s" - ) - - @pytest.mark.parametrize( - "configured", - [0, -5, float('inf'), float('-inf'), float('nan')], - ids=["zero", "negative", "inf", "-inf", "nan"], - ) - def test_polling_falls_back_to_the_default(self, configured, caplog): - caplog.set_level(logging.WARNING) - - state = for_polling(configured) - delay = failure_delay(state, NORMAL) - - assert state._operating_cadence == DEFAULT_POLL_INTERVAL - assert delay == DEFAULT_POLL_INTERVAL - assert math.isfinite(delay) and delay > 0 - assert caplog.records[0].getMessage() == ( - "poll_interval must be a positive, finite number of seconds; using the default of 30s" - ) - - @pytest.mark.parametrize("configured", [0.001, 0.5, 1, 5, 30]) - def test_a_positive_streaming_delay_is_left_alone(self, configured, caplog): - caplog.set_level(logging.WARNING) - - state = for_streaming(configured) - - assert state._min_delay == configured - assert failure_delay(state, NORMAL) == configured - assert caplog.records == [] - - @pytest.mark.parametrize("configured", [0.001, 1, 30, 300, 2 * 60 * 60]) - def test_a_positive_poll_interval_is_left_alone(self, configured, caplog): - caplog.set_level(logging.WARNING) - - state = for_polling(configured) - - assert state._operating_cadence == configured - assert failure_delay(state, NORMAL) == configured - assert caplog.records == [] - - -class TestStreamingCeilings: - """A configured reconnect delay longer than a regime's ceiling raises that - bound. The configured value wins over our default, rather than being cut - down to it.""" - - @pytest.mark.parametrize("configured", [600, 7200, 86400]) - def test_a_delay_past_the_normal_ceiling_raises_the_bound(self, configured): - assert failure_delay(for_streaming(configured), NORMAL) == configured - - @pytest.mark.parametrize("configured", [7200, 86400]) - def test_a_delay_past_the_extended_ceiling_raises_the_bound(self, configured): - assert failure_delay(for_streaming(configured), UNEXPECTED) == configured - - @pytest.mark.parametrize("configured", [0.5, 1, 30]) - def test_a_delay_within_the_normal_ceiling_is_untouched(self, configured): - assert failure_delay(for_streaming(configured), NORMAL) == configured - - -class TestStreamingExtendedDelayFloor: - """A delay that applies after an unexpected failure must not be below the - component's initial delay.""" - - @pytest.mark.parametrize( - "configured,expected", - [(1, 300), (30, 300), (300, 300), (600, 600), (3600, 3600), (0, 300), (-5, 300)], - ) - def test_the_extended_delay_never_starts_below_the_configured_delay(self, configured, expected): - assert failure_delay(for_streaming(configured), UNEXPECTED) == expected - - @pytest.mark.parametrize("configured", [1, 30, 300, 600, 3600]) - def test_an_unexpected_failure_never_waits_less_than_a_normal_one(self, configured): - normal = failure_delay(for_streaming(configured), NORMAL) - unexpected = failure_delay(for_streaming(configured), UNEXPECTED) - assert unexpected >= normal - - @pytest.mark.parametrize( - "configured,ladder", - [ - (1, [300, 600, 1200, 2400, 3600]), - (600, [600, 1200, 2400, 3600, 3600]), - ], - ids=["default", "clamped"], - ) - def test_the_extended_ladder_still_doubles_to_the_ceiling(self, configured, ladder): - state = for_streaming(configured) - delays = [failure_delay(state, UNEXPECTED)] - delays += [failure_delay(state, NORMAL) for _ in range(4)] - assert delays == ladder - - -class TestStreamingDelayTable: - def test_normal_regime_doubles_up_to_the_ceiling(self): - state = for_streaming(1) - delays = [failure_delay(state, NORMAL) for _ in range(8)] - assert delays == [1, 2, 4, 8, 16, 30, 30, 30] - - def test_extended_regime_doubles_up_to_the_ceiling(self): - state = for_streaming(1) - delays = [failure_delay(state, UNEXPECTED)] - delays += [failure_delay(state, NORMAL) for _ in range(5)] - assert delays == [5 * 60, 10 * 60, 20 * 60, 40 * 60, 60 * 60, 60 * 60] - - @pytest.mark.parametrize("configured", [1, 30, 45, 600]) - def test_the_ceiling_is_never_below_what_was_configured(self, configured): - # A configured delay longer than the normal ceiling raises the bound, so - # the first wait is never shorter than what the caller asked for. - assert for_streaming(configured)._max_delay == max(NORMAL_STREAMING_CEILING_DELAY, configured) - - def test_the_ceiling_is_sticky_once_the_extended_regime_starts(self): - # A normal failure after an unexpected one must not lower the bounds - # back to the normal regime. - state = for_streaming(1) - state.record_failure(UNEXPECTED) - assert state._extended - assert state._max_delay == EXTENDED_CEILING_DELAY - - state.record_failure(NORMAL) - assert state._extended - assert state._max_delay == EXTENDED_CEILING_DELAY - assert state._min_delay == EXTENDED_INITIAL_DELAY - - def test_a_second_unexpected_failure_keeps_counting_up(self): - # Restarting the count on every unexpected failure would pin the delay - # at the extended initial delay for ever. - state = for_streaming(1) - assert failure_delay(state, UNEXPECTED) == 5 * 60 - assert failure_delay(state, UNEXPECTED) == 10 * 60 - assert failure_delay(state, UNEXPECTED) == 20 * 60 - - def test_the_streaming_defaults_match_the_spec(self): - state = for_streaming(1) - assert state._max_delay == NORMAL_STREAMING_CEILING_DELAY - assert state._operating_cadence == 0 - assert STREAMING_RESET_INTERVAL == 60 - - -class TestJitter: - def test_jitter_never_removes_more_than_half_the_delay(self): - with fixed_retry_jitter(FULL_JITTER): - state = for_streaming(8) - delay = failure_delay(state, NORMAL) - assert 4 <= delay < 8 - - def test_no_jitter_leaves_the_delay_alone(self): - state = for_streaming(8) - assert failure_delay(state, NORMAL) == 8 - - def test_every_delay_stays_within_the_jitter_bounds(self): - # The real random source, so the bound has to hold for any draw rather - # than for one seeded sequence. - with real_jitter(): - state = for_streaming(1) - for base in [1, 2, 4, 8, 16, 30, 30, 30]: - delay = failure_delay(state, NORMAL) - assert base / 2 <= delay <= base - - -class TestWaitBetweenOperations: - def test_a_streaming_success_schedules_no_wait(self): - """Streaming's cadence is zero, and a success schedules the cadence.""" - state = for_streaming(1) - state.record_failure(NORMAL) - state.record_success() - - assert state.next_delay == 0 - - def test_a_zero_cadence_puts_no_floor_under_a_retry(self): - """The floor is the cadence, so streaming's jitter is free to take a - retry below the configured delay.""" - with fixed_retry_jitter(FULL_JITTER): - state = for_streaming(1) - assert failure_delay(state, NORMAL) == pytest.approx(0.5) - - def test_only_streaming_can_yield_a_zero_wait(self): - """Polling is the only data source that reads next_delay as a - DelaySource, so a zero there would busy-loop its scheduler. Its - cadence floor rules that out for every outcome.""" - state = for_polling(30) - assert state.next_delay == 30 - with real_jitter(): - for kind in (NORMAL, UNEXPECTED, NORMAL, UNEXPECTED): - state.record_failure(kind) - assert state.next_delay >= 30 - state.record_success() - assert state.next_delay == 30 - - def test_a_polling_success_schedules_the_cadence(self): - state = for_polling(30) - state.record_failure(NORMAL) - state.record_success() - - assert state.next_delay == 30 - - def test_a_fresh_state_and_a_success_agree(self): - """The constructor and record_success share one expression, so the two - cannot drift apart.""" - for state in (for_streaming(5), for_polling(45)): - fresh = state.next_delay - state.record_success() - assert state.next_delay == fresh - - -class TestStreamingReset: - def test_a_minute_of_healthy_operation_resets_the_state(self): - # The whole minute passes instantly. - with frozen_clock() as clock: - state = for_streaming(1) - state.record_failure(UNEXPECTED) - state.record_failure(NORMAL) - - state.record_success() - assert state._extended, "the window has not elapsed yet" - - clock.advance(STREAMING_RESET_INTERVAL) - state.record_success() - assert not state._extended - assert state._max_delay == NORMAL_STREAMING_CEILING_DELAY - assert failure_delay(state, NORMAL) == 1 - - def test_a_reset_also_happens_on_the_failure_that_ends_a_healthy_stretch(self): - with frozen_clock() as clock: - state = for_streaming(1) - state.record_failure(NORMAL) - state.record_failure(NORMAL) - - state.record_success() - clock.advance(STREAMING_RESET_INTERVAL) - - # The state resets before this failure is counted, so the delay is - # the first-retry delay again rather than the fourth. - assert failure_delay(state, NORMAL) == 1 - - def test_a_short_healthy_stretch_does_not_reset(self): - with frozen_clock() as clock: - state = for_streaming(1) - state.record_failure(NORMAL) - - state.record_success() - clock.advance(STREAMING_RESET_INTERVAL - 1) - assert failure_delay(state, NORMAL) == 2 - - def test_a_fast_flapping_connection_does_not_ratchet_into_the_extended_regime(self): - # Every transport failure is normal, so no amount of flapping reaches - # the extended regime. Each cycle is a healthy stretch shorter than the - # reset window, so the delay climbs, but only to the normal ceiling. - with frozen_clock() as clock: - state = for_streaming(1) - delays = [] - for _ in range(20): - state.record_success() - clock.advance(5) - delays.append(failure_delay(state, NORMAL)) - clock.advance(1) - - assert not state._extended - assert max(delays) == NORMAL_STREAMING_CEILING_DELAY - assert state._max_delay == NORMAL_STREAMING_CEILING_DELAY - - -class TestPollingCadence: - def test_a_normal_failure_polls_again_on_schedule(self): - state = for_polling(30) - assert [failure_delay(state, NORMAL) for _ in range(4)] == [30, 30, 30, 30] - - def test_the_extended_regime_doubles_up_to_an_hour(self): - state = for_polling(30) - delays = [failure_delay(state, UNEXPECTED)] - delays += [failure_delay(state, NORMAL) for _ in range(5)] - assert delays == [5 * 60, 10 * 60, 20 * 60, 40 * 60, 60 * 60, 60 * 60] - - def test_the_wait_never_falls_below_the_poll_interval(self): - # Full jitter would otherwise halve the delay. - with fixed_retry_jitter(FULL_JITTER): - state = for_polling(30) - assert failure_delay(state, NORMAL) == 30 - assert failure_delay(state, UNEXPECTED) >= 30 - - def test_a_poll_interval_longer_than_the_extended_bounds_wins(self): - """Unlike the streaming delay, the poll interval is not clamped to the - extended ceiling. Nothing may poll faster than the configured interval, - so the cadence wins where the two conflict.""" - two_hours = 2 * 60 * 60 - assert two_hours > EXTENDED_CEILING_DELAY - - state = for_polling(two_hours) - - assert failure_delay(state, UNEXPECTED) == two_hours - assert state._max_delay == two_hours - assert state._min_delay == two_hours - assert failure_delay(state, NORMAL) == two_hours - state.record_success() - assert state.next_delay == two_hours - - def test_one_success_restores_the_cadence_while_the_state_is_still_raised(self): - # A backoff wait applies to a retry, not to every operation. - # Conflating this with the reset would leave the first successful poll - # after an outage still waiting twenty minutes. - state = for_polling(30) - state.record_failure(UNEXPECTED) - state.record_failure(NORMAL) - assert failure_delay(state, NORMAL) == 20 * 60 - - state.record_success() - assert state.next_delay == 30 - assert state._extended, "one success does not reset the state" - - def test_two_successes_in_a_row_reset_the_state(self): - state = for_polling(30) - state.record_failure(UNEXPECTED) - - state.record_success() - assert state._extended - - state.record_success() - assert not state._extended - assert state.next_delay == 30 - assert failure_delay(state, NORMAL) == 30 - - def test_a_failure_between_two_successes_clears_the_first(self): - state = for_polling(30) - state.record_failure(UNEXPECTED) - state.record_success() - state.record_failure(NORMAL) - state.record_success() - assert state._extended - - state.record_success() - assert not state._extended - - def test_the_polling_defaults_match_the_spec(self): - state = for_polling(30) - assert state._operating_cadence == 30 - assert state._min_delay == 30 - assert state._max_delay == 30 - assert POLLING_RESET_SUCCESSES == 2 - - -class TestAttemptCount: - def test_attempts_counts_every_failure(self): - state = for_streaming(1) - for _ in range(5): - state.record_failure(NORMAL) - assert state._attempts == 5 - - def test_a_reset_starts_the_attempt_count_over(self): - # A reset clears the counter, so the next failure is attempt 1. - with frozen_clock() as clock: - state = for_streaming(1) - state.record_failure(NORMAL) - state.record_failure(NORMAL) - assert state._attempts == 2 - - state.record_success() - clock.advance(STREAMING_RESET_INTERVAL) - state.record_success() - - # The delay drops back to the first-retry value, and the count - # starts over with it. - assert failure_delay(state, NORMAL) == 1 - assert state._attempts == 1 - - -class TestResetPolicies: - def test_healthy_for_tracks_the_start_of_the_stretch(self): - with frozen_clock() as clock: - policy = AfterHealthyFor(60) - assert not policy.is_satisfied() - - policy.note_healthy() - started = policy._healthy_since - - # A later signal must not push the start of the stretch out. - clock.advance(40) - policy.note_healthy() - assert policy._healthy_since == started - - clock.advance(20) - assert policy.is_satisfied() - - def test_many_healthy_signals_do_not_move_the_window(self): - """Streaming signals on every message, so an unconditional assignment - here would push its reset out for ever.""" - with frozen_clock() as clock: - policy = AfterHealthyFor(60) - policy.note_healthy() - first = policy._healthy_since - - for _ in range(59): - clock.advance(1) - policy.note_healthy() - - assert policy._healthy_since == first - assert not policy.is_satisfied() - - # The threshold lands 60s after the first signal, not the last. - clock.advance(1) - policy.note_healthy() - assert policy.is_satisfied() - - def test_healthy_for_is_cleared_by_a_failure(self): - with frozen_clock() as clock: - policy = AfterHealthyFor(60) - policy.note_healthy() - policy.note_failure() - assert policy._healthy_since is None - - clock.advance(900) - assert not policy.is_satisfied() - - def test_consecutive_successes_counts_up(self): - policy = AfterConsecutiveSuccesses(2) - policy.note_healthy() - assert not policy.is_satisfied() - policy.note_healthy() - assert policy.is_satisfied() - - def test_consecutive_successes_is_cleared_by_a_failure(self): - policy = AfterConsecutiveSuccesses(2) - policy.note_healthy() - policy.note_failure() - assert policy._successes == 0 - assert not policy.is_satisfied() - - -class TestLongOutage: - def test_a_long_outage_cannot_overflow_the_delay(self): - state = RetryState( - normal_initial_delay=1, - normal_ceiling_delay=30, - extended_initial_delay=EXTENDED_INITIAL_DELAY, - extended_ceiling_delay=EXTENDED_CEILING_DELAY, - reset_policy=AfterHealthyFor(60), - ) - for _ in range(5000): - delay = failure_delay(state, NORMAL) - assert delay == 30 diff --git a/ldclient/testing/integrations/test_dynamodb.py b/ldclient/testing/integrations/test_dynamodb.py index 512e63bf..f820b1a4 100644 --- a/ldclient/testing/integrations/test_dynamodb.py +++ b/ldclient/testing/integrations/test_dynamodb.py @@ -9,7 +9,6 @@ _DynamoDBHelpers ) from ldclient.integrations import DynamoDB -from ldclient.interfaces import UpdateProcessor from ldclient.testing.integrations.big_segment_store_test_base import * from ldclient.testing.integrations.persistent_feature_store_test_base import * from ldclient.testing.test_util import skip_database_tests diff --git a/ldclient/testing/integrations/test_file_data_sourcev2.py b/ldclient/testing/integrations/test_file_data_sourcev2.py index 388180b5..10569d65 100644 --- a/ldclient/testing/integrations/test_file_data_sourcev2.py +++ b/ldclient/testing/integrations/test_file_data_sourcev2.py @@ -30,6 +30,13 @@ except ImportError: pass +have_watchdog = False +try: + import watchdog + have_watchdog = True +except ImportError: + pass + all_properties_json = ''' { @@ -473,3 +480,69 @@ def test_accepts_single_path_string(): assert len(result.value.change_set.changes) == 1 finally: os.remove(path) + + +unsafe_yaml_caused_method_to_be_called = False + + +def arbitrary_method_called_from_yaml(x): + global unsafe_yaml_caused_method_to_be_called + unsafe_yaml_caused_method_to_be_called = True + + +def test_initializer_does_not_allow_unsafe_yaml(): + if not have_yaml: + pytest.skip("skipping YAML test because pyyaml isn't available") + + # This extended syntax defined by pyyaml allows arbitrary code execution. The data source + # must use yaml.safe_load(), which does not support it. + unsafe_yaml = ''' +!!python/object/apply:ldclient.testing.integrations.test_file_data_sourcev2.arbitrary_method_called_from_yaml ["hi"] +''' + path = make_temp_file(unsafe_yaml) + try: + initializer = Files.new_data_source_v2(paths=[path]).build(Config(sdk_key="dummy")) + result = initializer.fetch(MockSelectorStore(Selector.no_selector())) + assert isinstance(result, _Fail) + finally: + os.remove(path) + assert unsafe_yaml_caused_method_to_be_called is False + + +def test_synchronizer_detects_file_changes_with_watchdog(): + """Test that the synchronizer detects a file change through the native file watcher.""" + if not have_watchdog: + pytest.skip("skipping watchdog test because watchdog isn't available") + + def has_segment(update): + return update.change_set is not None and any(c.kind == ObjectKind.SEGMENT for c in update.change_set.changes) + + path = make_temp_file(flag_only_json) + synchronizer = Files.new_data_source_v2(paths=[path]).build(Config(sdk_key="dummy")) + try: + initial = threading.Event() + reloaded = threading.Event() + + def collect_updates(): + # The watcher can see the file while it is partly written, so an error update + # can come before the update that has the new data. + for update in synchronizer.sync(MockSelectorStore(Selector.no_selector())): + initial.set() + if has_segment(update): + reloaded.set() + break + + sync_thread = threading.Thread(target=collect_updates) + sync_thread.start() + + assert initial.wait(timeout=2), "Did not receive initial update" + time.sleep(0.5) + replace_file(path, segment_only_json) + + assert reloaded.wait(timeout=20), "Did not receive the new data after the file change" + + synchronizer.stop() + sync_thread.join(timeout=2) + finally: + synchronizer.stop() + os.remove(path) diff --git a/ldclient/testing/integrations/test_test_data_source.py b/ldclient/testing/integrations/test_test_data_source.py deleted file mode 100644 index ddadeb39..00000000 --- a/ldclient/testing/integrations/test_test_data_source.py +++ /dev/null @@ -1,317 +0,0 @@ -from typing import Callable - -import pytest - -from ldclient.client import Context, LDClient -from ldclient.config import Config -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.integrations.test_data import FlagBuilder, TestData -from ldclient.versioned_data_kind import FEATURES - -# Test Data + Data Source - - -def test_makes_valid_datasource(): - td = TestData.data_source() - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store)) - - assert store.all(FEATURES, lambda x: x) == {} - - -def verify_flag_builder(desc: str, expected_props: dict, builder_actions: Callable[[FlagBuilder], FlagBuilder]): - all_expected_props = { - 'key': 'test-flag', - 'version': 1, - 'on': True, - 'prerequisites': [], - 'targets': [], - 'contextTargets': [], - 'rules': [], - 'salt': '', - 'variations': [True, False], - 'offVariation': 1, - 'fallthrough': {'variation': 0}, - } - all_expected_props.update(expected_props) - - td = TestData.data_source() - flag_builder = builder_actions(td.flag(key='test-flag')) - built_flag = flag_builder._build(1) - assert built_flag == all_expected_props, "did not get expected flag properties for '%s' test" % desc - - -@pytest.mark.parametrize( - 'expected_props,builder_actions', - [ - pytest.param({}, lambda f: f, id='defaults'), - pytest.param({}, lambda f: f.boolean_flag(), id='changing default flag to boolean flag has no effect'), - pytest.param( - {}, - lambda f: f.variations('a', 'b').boolean_flag(), - id='non-boolean flag can be changed to boolean flag', - ), - pytest.param({'on': False}, lambda f: f.on(False), id='flag can be turned off'), - pytest.param( - {}, - lambda f: f.on(False).on(True), - id='flag can be turned on', - ), - pytest.param({'fallthrough': {'variation': 1}}, lambda f: f.variation_for_all(False), id='set false variation for all'), - pytest.param({'fallthrough': {'variation': 0}}, lambda f: f.variation_for_all(True), id='set true variation for all'), - pytest.param({'variations': ['a', 'b', 'c'], 'fallthrough': {'variation': 2}}, lambda f: f.variations('a', 'b', 'c').variation_for_all(2), id='set variation index for all'), - pytest.param({'offVariation': 0}, lambda f: f.off_variation(True), id='set off variation boolean'), - pytest.param({'variations': ['a', 'b', 'c'], 'offVariation': 2}, lambda f: f.variations('a', 'b', 'c').off_variation(2), id='set off variation index'), - pytest.param({'variations': ['x'], 'offVariation': 0}, lambda f: f.value_for_all('x'), id='value for all'), - pytest.param({'on': False, 'variations': ['x'], 'offVariation': 0}, lambda f: f.value_for_all('x').on(False), id='value for all with targeting off'), - pytest.param( - { - 'targets': [ - {'variation': 0, 'values': ['key1', 'key2']}, - ], - 'contextTargets': [ - {'contextKind': 'user', 'variation': 0, 'values': []}, - {'contextKind': 'kind1', 'variation': 0, 'values': ['key3', 'key4']}, - {'contextKind': 'kind1', 'variation': 1, 'values': ['key5', 'key6']}, - ], - }, - lambda f: f.variation_for_key('user', 'key1', True) - .variation_for_key('user', 'key2', True) - .variation_for_key('kind1', 'key3', True) - .variation_for_key('kind1', 'key5', False) - .variation_for_key('kind1', 'key4', True) - .variation_for_key('kind1', 'key6', False), - id='set context targets as boolean', - ), - pytest.param( - { - 'variations': ['a', 'b'], - 'targets': [ - {'variation': 0, 'values': ['key1', 'key2']}, - ], - 'contextTargets': [ - {'contextKind': 'user', 'variation': 0, 'values': []}, - {'contextKind': 'kind1', 'variation': 0, 'values': ['key3', 'key4']}, - {'contextKind': 'kind1', 'variation': 1, 'values': ['key5', 'key6']}, - ], - }, - lambda f: f.variations('a', 'b') - .variation_for_key('user', 'key1', 0) - .variation_for_key('user', 'key2', 0) - .variation_for_key('kind1', 'key3', 0) - .variation_for_key('kind1', 'key5', 1) - .variation_for_key('kind1', 'key4', 0) - .variation_for_key('kind1', 'key6', 1), - id='set context targets as variation index', - ), - pytest.param( - {'contextTargets': [{'contextKind': 'kind1', 'variation': 0, 'values': ['key1', 'key2']}, {'contextKind': 'kind1', 'variation': 1, 'values': ['key3']}]}, - lambda f: f.variation_for_key('kind1', 'key1', 0).variation_for_key('kind1', 'key2', 1).variation_for_key('kind1', 'key3', 1).variation_for_key('kind1', 'key2', 0), - id='replace existing context target key', - ), - pytest.param( - { - 'variations': ['a', 'b'], - 'contextTargets': [ - {'contextKind': 'kind1', 'variation': 1, 'values': ['key1']}, - ], - }, - lambda f: f.variations('a', 'b').variation_for_key('kind1', 'key1', 1).variation_for_key('kind1', 'key2', 3), - id='ignore target for nonexistent variation', - ), - pytest.param( - {'targets': [{'variation': 0, 'values': ['key1']}], 'contextTargets': [{'contextKind': 'user', 'variation': 0, 'values': []}]}, - lambda f: f.variation_for_user('key1', True), - id='variation_for_user is shortcut for variation_for_key', - ), - pytest.param({}, lambda f: f.variation_for_key('kind1', 'key1', 0).clear_targets(), id='clear targets'), - pytest.param( - {'rules': [{'variation': 1, 'id': 'rule0', 'clauses': [{'contextKind': 'kind1', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': False}]}]}, - lambda f: f.if_match_context('kind1', 'attr1', 'a', 'b').then_return(1), - id='if_match_context', - ), - pytest.param( - {'rules': [{'variation': 1, 'id': 'rule0', 'clauses': [{'contextKind': 'kind1', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': True}]}]}, - lambda f: f.if_not_match_context('kind1', 'attr1', 'a', 'b').then_return(1), - id='if_not_match_context', - ), - pytest.param( - {'rules': [{'variation': 1, 'id': 'rule0', 'clauses': [{'contextKind': 'user', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': False}]}]}, - lambda f: f.if_match('attr1', 'a', 'b').then_return(1), - id='if_match is shortcut for if_match_context', - ), - pytest.param( - {'rules': [{'variation': 1, 'id': 'rule0', 'clauses': [{'contextKind': 'user', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': True}]}]}, - lambda f: f.if_not_match('attr1', 'a', 'b').then_return(1), - id='if_not_match is shortcut for if_not_match_context', - ), - pytest.param( - { - 'rules': [ - { - 'variation': 1, - 'id': 'rule0', - 'clauses': [ - {'contextKind': 'kind1', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': False}, - {'contextKind': 'kind1', 'attribute': 'attr2', 'op': 'in', 'values': ['c', 'd'], 'negate': False}, - ], - } - ] - }, - lambda f: f.if_match_context('kind1', 'attr1', 'a', 'b').and_match_context('kind1', 'attr2', 'c', 'd').then_return(1), - id='and_match_context', - ), - pytest.param( - { - 'rules': [ - { - 'variation': 1, - 'id': 'rule0', - 'clauses': [ - {'contextKind': 'kind1', 'attribute': 'attr1', 'op': 'in', 'values': ['a', 'b'], 'negate': False}, - {'contextKind': 'kind1', 'attribute': 'attr2', 'op': 'in', 'values': ['c', 'd'], 'negate': True}, - ], - } - ] - }, - lambda f: f.if_match_context('kind1', 'attr1', 'a', 'b').and_not_match_context('kind1', 'attr2', 'c', 'd').then_return(1), - id='and_not_match_context', - ), - pytest.param({}, lambda f: f.if_match_context('kind1', 'attr1', 'a').then_return(1).clear_rules(), id='clear rules'), - ], -) -def test_flag_configs_parameterized(expected_props: dict, builder_actions: Callable[[FlagBuilder], FlagBuilder]): - verify_flag_builder('x', expected_props, builder_actions) - - -def test_can_retrieve_flag_from_store(): - td = TestData.data_source() - td.update(td.flag('some-flag')) - - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store)) - - assert store.get(FEATURES, 'some-flag') == FEATURES.decode(td.flag('some-flag')._build(1)) - - client.close() - - -def test_updates_to_flags_are_reflected_in_store(): - td = TestData.data_source() - - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store)) - - td.update(td.flag('some-flag')) - - assert store.get(FEATURES, 'some-flag') == FEATURES.decode(td.flag('some-flag')._build(1)) - - client.close() - - -def test_updates_after_client_close_have_no_affect(): - td = TestData.data_source() - - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store)) - - client.close() - - td.update(td.flag('some-flag')) - - assert store.get(FEATURES, 'some-flag') is None - - -def test_can_handle_multiple_clients(): - td = TestData.data_source() - flag_builder = td.flag('flag') - built_flag = flag_builder._build(1) - td.update(flag_builder) - - store = InMemoryFeatureStore() - store2 = InMemoryFeatureStore() - - config = Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store) - client = LDClient(config=config) - - config2 = Config('SDK_KEY', update_processor_class=td, send_events=False, offline=True, feature_store=store2) - client2 = LDClient(config=config2) - - assert store.get(FEATURES, 'flag') == FEATURES.decode(built_flag) - - assert store2.get(FEATURES, 'flag') == FEATURES.decode(built_flag) - - flag_builder_v2 = td.flag('flag').variation_for_all(False) - td.update(flag_builder_v2) - built_flag_v2 = flag_builder_v2._build(2) - - assert store.get(FEATURES, 'flag') == FEATURES.decode(built_flag_v2) - - assert store2.get(FEATURES, 'flag') == FEATURES.decode(built_flag_v2) - - client.close() - client2.close() - - -def test_flag_evaluation_with_client(): - td = TestData.data_source() - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, feature_store=store)) - - td.update(td.flag(key='test-flag').fallthrough_variation(False).if_match('firstName', 'Mike').and_not_match('country', 'gb').then_return(True)) - - # user1 should satisfy the rule (matching firstname, not matching country) - user1 = Context.from_dict({'kind': 'user', 'key': 'user1', 'firstName': 'Mike', 'country': 'us'}) - eval1 = client.variation_detail('test-flag', user1, default='default') - - assert eval1.value is True - assert eval1.variation_index == 0 - assert eval1.reason['kind'] == 'RULE_MATCH' - - # user2 should NOT satisfy the rule (not matching firstname despite not matching country) - user2 = Context.from_dict({'kind': 'user', 'key': 'user2', 'firstName': 'Joe', 'country': 'us'}) - eval2 = client.variation_detail('test-flag', user2, default='default') - - assert eval2.value is False - assert eval2.variation_index == 1 - assert eval2.reason['kind'] == 'FALLTHROUGH' - - -def test_value_for_all_evaluates_to_value_when_targeting_is_off(): - td = TestData.data_source() - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, feature_store=store)) - - td.update(td.flag(key='test-flag').value_for_all('x').on(False)) - - detail = client.variation_detail('test-flag', Context.create('user1'), default='default') - - assert detail.value == 'x' - assert detail.variation_index == 0 - assert detail.reason['kind'] == 'OFF' - - -def test_flag_can_evaluate_all_flags(): - td = TestData.data_source() - store = InMemoryFeatureStore() - - client = LDClient(config=Config('SDK_KEY', update_processor_class=td, send_events=False, feature_store=store)) - - td.update(td.flag(key='test-flag').fallthrough_variation(False).if_match('firstName', 'Mike').and_not_match('country', 'gb').then_return(True)) - - user1 = Context.from_dict({'kind': 'user', 'key': 'user1', 'firstName': 'Mike', 'country': 'us'}) - flags_state = client.all_flags_state(user1, with_reasons=True) - - assert flags_state.valid - - value = flags_state.get_flag_value('test-flag') - reason = flags_state.get_flag_reason('test-flag') or {} - - assert value is True - assert reason.get('kind', None) == 'RULE_MATCH' diff --git a/ldclient/testing/mock_async_components.py b/ldclient/testing/mock_async_components.py index 9e5b74f7..b92171ba 100644 --- a/ldclient/testing/mock_async_components.py +++ b/ldclient/testing/mock_async_components.py @@ -3,9 +3,7 @@ """ from ldclient.async_feature_store import AsyncInMemoryFeatureStore -from ldclient.impl.datasource.async_status import AsyncDataSourceUpdateSinkImpl -from ldclient.impl.listeners import Listeners -from ldclient.interfaces import AsyncEventProcessor, AsyncUpdateProcessor +from ldclient.interfaces import AsyncEventProcessor class MockAsyncEventProcessor(AsyncEventProcessor): @@ -58,35 +56,3 @@ async def force_delete(self, kind, key): Useful for tearing down test state without going through the delete tombstone mechanism. """ self._items[kind].pop(key, None) - - -class MockAsyncUpdateProcessor(AsyncUpdateProcessor): - """A mock UpdateProcessor that immediately reports itself as initialized. - - Used to fake a ready data source in client tests. If a ``ready`` event is provided, it is - set immediately in the constructor, matching the behavior of the sync ``MockUpdateProcessor``. - """ - - def __init__(self, config=None, store=None, ready=None): - if ready is not None: - ready.set() - - def start(self): - pass - - async def stop(self): - pass - - def initialized(self) -> bool: - return True - - -def with_async_update_sink(config, store): - """ - Gives the config an async data source update sink that writes to the - store, if the config has no sink. The data system does this for a real - client. Returns the config. - """ - if config.data_source_update_sink is None: - config._data_source_update_sink = AsyncDataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - return config diff --git a/ldclient/testing/mock_components.py b/ldclient/testing/mock_components.py index 6bf3a2ce..ad93b32b 100644 --- a/ldclient/testing/mock_components.py +++ b/ldclient/testing/mock_components.py @@ -1,8 +1,6 @@ import time from typing import Callable -from ldclient.impl.datasource.status import DataSourceUpdateSinkImpl -from ldclient.impl.listeners import Listeners from ldclient.interfaces import ( BigSegmentStore, BigSegmentStoreMetadata, @@ -56,14 +54,3 @@ def __init__(self, selector: Selector): def selector(self) -> Selector: return self._selector - - -def with_update_sink(config, store): - """ - Gives the config a data source update sink that writes to the store, if - the config has no sink. The data system does this for a real client. - Returns the config. - """ - if config.data_source_update_sink is None: - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, Listeners(), Listeners()) - return config diff --git a/ldclient/testing/stub_util.py b/ldclient/testing/stub_util.py index 2d808f0a..d78ef599 100644 --- a/ldclient/testing/stub_util.py +++ b/ldclient/testing/stub_util.py @@ -1,15 +1,8 @@ import gzip -import json from email.utils import formatdate -from ldclient.impl.model import ModelEntity -from ldclient.interfaces import ( - EventProcessor, - FeatureRequester, - FeatureStore, - UpdateProcessor -) -from ldclient.testing.http_util import ChunkedResponse, JsonResponse +from ldclient.interfaces import EventProcessor, FeatureStore +from ldclient.testing.http_util import ChunkedResponse def decode_request_body(headers, body): @@ -19,38 +12,6 @@ def decode_request_body(headers, body): return body -def item_as_json(item): - return item.to_json_dict() if isinstance(item, ModelEntity) else item - - -def make_items_map(items=[]): - ret = {} - for item in items: - ret[item['key']] = item_as_json(item) - return ret - - -def make_put_event(flags=[], segments=[]): - data = {"data": {"flags": make_items_map(flags), "segments": make_items_map(segments)}} - return 'event:put\ndata: %s\n\n' % json.dumps(data) - - -def make_invalid_put_event(): - return 'event:put\ndata: {"data": {\n\n' - - -def make_patch_event(kind, item): - path = '%s%s' % (kind.stream_api_path, item['key']) - data = {"path": path, "data": item_as_json(item)} - return 'event:patch\ndata: %s\n\n' % json.dumps(data) - - -def make_delete_event(kind, key, version): - path = '%s%s' % (kind.stream_api_path, key) - data = {"path": path, "version": version} - return 'event:delete\ndata: %s\n\n' % json.dumps(data) - - def stream_content(event=None, headers=None): stream_headers = {'Content-Type': 'text/event-stream'} stream_headers.update(headers or {}) @@ -60,11 +21,6 @@ def stream_content(event=None, headers=None): return stream -def poll_content(flags=[], segments=[], headers=None): - data = {"flags": make_items_map(flags), "segments": make_items_map(segments)} - return JsonResponse(data, headers) - - class MockEventProcessor(EventProcessor): def __init__(self, *_): self._running = False @@ -83,19 +39,6 @@ def flush(self): pass -class MockFeatureRequester(FeatureRequester): - def __init__(self): - self.all_data = {} - self.exception = None - self.request_count = 0 - - def get_all_data(self): - self.request_count += 1 - if self.exception is not None: - raise self.exception - return self.all_data - - class _MockHTTPHeaderDict(dict): def __init__(self, d): super().__init__({k.lower(): v for k, v in d.items()}) @@ -178,20 +121,6 @@ def reset(self): self._recorded_requests = [] -class MockUpdateProcessor(UpdateProcessor): - def __init__(self, config, store, ready): - ready.set() - - def start(self): - pass - - def stop(self): - pass - - def initialized(self): - return True - - class CapturingFeatureStore(FeatureStore): def init(self, all_data): self.data = all_data diff --git a/ldclient/testing/test_async_client.py b/ldclient/testing/test_async_client.py index 33079805..f4fdd287 100644 --- a/ldclient/testing/test_async_client.py +++ b/ldclient/testing/test_async_client.py @@ -45,6 +45,30 @@ def _daemon_config(store, **kwargs): ) +class _SilentAsyncSynchronizer: + """An async synchronizer that sends no data until it stops.""" + + def __init__(self): + self._stopped = asyncio.Event() + + @property + def name(self) -> str: + return 'silent' + + async def sync(self, ss): + await self._stopped.wait() + return + yield + + async def stop(self): + self._stopped.set() + + +class _SilentAsyncSynchronizerBuilder: + def build(self, config): + return _SilentAsyncSynchronizer() + + def _make_flag(key: str, value, version: int = 1) -> dict: """Build a minimal feature flag dict usable with AsyncInMemoryFeatureStore.""" return { @@ -461,10 +485,18 @@ async def fake_evaluate(flag, context, event_factory): async def test_cached_data_warnings_are_logged_once_per_client(caplog): caplog.set_level(logging.WARNING, logger='ldclient.util') store = MockAsyncFeatureStore() - await store.force_set(FEATURES, _make_flag('my-flag', 'hello')) - # Daemon mode reports cached data, so every evaluation reads last known values. - client = AsyncLDClient(_daemon_config(store, send_events=False)) - await client.start(start_wait=1.0) + await store.init({FEATURES: {'my-flag': _make_flag('my-flag', 'hello')}}) + # The data source never sends data, so the client serves cached values from the store. + client = AsyncLDClient(AsyncConfig( + "test-sdk-key", + send_events=False, + datasystem_config=AsyncDataSystemConfig( + synchronizers=[_SilentAsyncSynchronizerBuilder()], + data_store=store, + data_store_mode=DataStoreMode.READ_ONLY, + ), + )) + await client.start(start_wait=0) assert await client.is_initialized() context = Context.create('user-1') @@ -482,3 +514,72 @@ async def test_cached_data_warnings_are_logged_once_per_client(caplog): assert all_flags_warnings[0].endswith('This message is logged once.') await client.close() + + +@pytest.mark.asyncio +async def test_daemon_mode_does_not_log_cached_data_warnings(caplog): + caplog.set_level(logging.WARNING, logger='ldclient.util') + store = MockAsyncFeatureStore() + await store.force_set(FEATURES, _make_flag('my-flag', 'hello')) + client = AsyncLDClient(_daemon_config(store, send_events=False)) + await client.start(start_wait=1.0) + context = Context.create('user-1') + + assert await client.variation('my-flag', context, 'default') == 'hello' + assert (await client.all_flags_state(context)).valid + await client.close() + + warnings = [r.message for r in caplog.records if r.levelname == 'WARNING'] + assert [m for m in warnings if m.startswith('Feature Flag evaluation attempted') or m.startswith('all_flags_state() called before')] == [] + + +@pytest.mark.asyncio +async def test_data_system_with_no_sources_and_no_store_logs_a_warning(caplog): + caplog.set_level(logging.INFO) + client = AsyncLDClient(AsyncConfig("test-sdk-key", send_events=False, datasystem_config=AsyncDataSystemConfig())) + await client.start(start_wait=0) + await client.close() + + assert "daemon mode" not in caplog.text + assert any( + r.levelname == "WARNING" and "no data sources and no persistent store" in r.message + for r in caplog.records + ) + + +@pytest.mark.asyncio +async def test_offline_mode_with_a_daemon_config_logs_only_offline_mode(caplog): + caplog.set_level(logging.INFO) + client = AsyncLDClient(_daemon_config(MockAsyncFeatureStore(), send_events=False, offline=True)) + await client.start(start_wait=0) + await client.close() + + assert "Started LaunchDarkly Client in offline mode" in caplog.text + assert "daemon mode" not in caplog.text + + +@pytest.mark.asyncio +async def test_daemon_mode_logs_daemon_mode(caplog): + caplog.set_level(logging.INFO) + client = AsyncLDClient(_daemon_config(MockAsyncFeatureStore(), send_events=False)) + await client.start(start_wait=0) + await client.close() + + assert "Started LaunchDarkly Client in daemon mode" in caplog.text + + +def test_client_uses_the_default_data_system_when_none_is_set(): + from ldclient.impl.datasourcev2.async_polling import ( + AsyncFallbackToFDv1PollingDataSourceBuilder, + AsyncPollingDataSourceBuilder + ) + from ldclient.impl.datasourcev2.async_streaming import ( + AsyncStreamingDataSourceBuilder + ) + + client = AsyncLDClient(AsyncConfig("test-sdk-key", send_events=False)) + dsc = client._datasystem_config + assert [type(b) for b in dsc.initializers] == [AsyncPollingDataSourceBuilder] + assert [type(b) for b in dsc.synchronizers] == [AsyncStreamingDataSourceBuilder, AsyncPollingDataSourceBuilder] + assert isinstance(dsc.fdv1_fallback_synchronizer, AsyncFallbackToFDv1PollingDataSourceBuilder) + assert dsc.data_store is None diff --git a/ldclient/testing/test_async_hooks.py b/ldclient/testing/test_async_hooks.py index af65db36..b556bf7d 100644 --- a/ldclient/testing/test_async_hooks.py +++ b/ldclient/testing/test_async_hooks.py @@ -7,6 +7,7 @@ import pytest +from ldclient import async_datasystem from ldclient.async_client import AsyncLDClient from ldclient.async_config import AsyncConfig from ldclient.context import Context @@ -18,10 +19,7 @@ Plugin, PluginMetadata ) -from ldclient.testing.mock_async_components import ( - MockAsyncFeatureStore, - MockAsyncUpdateProcessor -) +from ldclient.testing.mock_async_components import MockAsyncFeatureStore from ldclient.versioned_data_kind import FEATURES @@ -146,8 +144,7 @@ def after_evaluation(self, series_context, data, detail): store._initialized = True config = AsyncConfig( "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, + datasystem_config=async_datasystem.daemon(store).build(), send_events=False, hooks=[ContextVarHook()], ) @@ -237,8 +234,7 @@ async def get(self, kind, key): store._initialized = True config = AsyncConfig( "test-sdk-key", - feature_store=store, - update_processor_class=MockAsyncUpdateProcessor, + datasystem_config=async_datasystem.daemon(store).build(), send_events=False, hooks=[ContextVarHook()], ) diff --git a/ldclient/testing/test_config.py b/ldclient/testing/test_config.py index 6f15d969..29246f35 100644 --- a/ldclient/testing/test_config.py +++ b/ldclient/testing/test_config.py @@ -1,5 +1,6 @@ import pytest +from ldclient import datasystem from ldclient.async_config import AsyncConfig from ldclient.config import DEFAULT_POLL_INTERVAL, Config @@ -9,28 +10,15 @@ CONFIG_IDS = ["Config", "AsyncConfig"] -def test_copy_config(): - old_sdk_key = "OLD_SDK_KEY" - new_sdk_key = "NEW_SDK_KEY" - - old_config = Config(sdk_key=old_sdk_key, stream=False) - - assert old_config.sdk_key is old_sdk_key - assert old_config.stream is False - - new_config = old_config.copy_with_new_sdk_key(new_sdk_key) - assert new_config.sdk_key is new_sdk_key - assert new_config.stream is False - - def test_with_wrapper_information(): - config = Config(sdk_key="SDK_KEY", stream=False, wrapper_name="original", wrapper_version="1.0.0") + dsc = datasystem.polling().build() + config = Config(sdk_key="SDK_KEY", datasystem_config=dsc, wrapper_name="original", wrapper_version="1.0.0") wrapped = config.with_wrapper_information("wrapper", "2.0.0") assert wrapped.wrapper_name == "wrapper" assert wrapped.wrapper_version == "2.0.0" assert wrapped.sdk_key == "SDK_KEY" - assert wrapped.stream is False + assert wrapped.datasystem_config is dsc assert config.wrapper_name == "original" assert config.wrapper_version == "1.0.0" @@ -158,17 +146,6 @@ def test_sdk_key_validation_max_length(): assert config.sdk_key == '' -def test_copy_with_new_sdk_key_validation(): - """Test that copy_with_new_sdk_key validates the new key""" - original_config = Config(sdk_key="valid-key") - - new_config = original_config.copy_with_new_sdk_key("another-valid-key") - assert new_config.sdk_key == "another-valid-key" - - invalid_config = original_config.copy_with_new_sdk_key("invalid key with spaces") - assert invalid_config.sdk_key == '' - - def application_can_be_set_and_read(): application = {"id": "my-id", "version": "abcdef"} config = Config(sdk_key="SDK_KEY", application=application) diff --git a/ldclient/testing/test_file_data_source.py b/ldclient/testing/test_file_data_source.py deleted file mode 100644 index b10c378c..00000000 --- a/ldclient/testing/test_file_data_source.py +++ /dev/null @@ -1,345 +0,0 @@ -import json -import os -import tempfile -import threading -import time -from typing import List - -import pytest - -from ldclient.client import Context, LDClient -from ldclient.config import Config -from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.datasource.status import DataSourceUpdateSinkImpl -from ldclient.impl.listeners import Listeners -from ldclient.integrations import Files -from ldclient.interfaces import ( - DataSourceErrorKind, - DataSourceState, - DataSourceStatus -) -from ldclient.testing.mock_components import with_update_sink -from ldclient.testing.test_util import SpyListener -from ldclient.versioned_data_kind import FEATURES, SEGMENTS - -# Skip all tests in this module in CI due to flakiness -pytestmark = pytest.mark.skipif( - os.getenv('LD_SKIP_FLAKY_TESTS', '').lower() in ('true', '1', 'yes'), - reason="Skipping flaky test" -) - -have_yaml = False -try: - import yaml - - have_yaml = True -except ImportError: - pass - - -all_flag_keys = ['flag1', 'flag2'] -all_properties_json = ''' - { - "flags": { - "flag1": { - "key": "flag1", - "on": true, - "fallthrough": { - "variation": 2 - }, - "variations": [ "fall", "off", "on" ] - } - }, - "flagValues": { - "flag2": "value2" - }, - "segments": { - "seg1": { - "key": "seg1", - "include": ["user1"] - } - } - } -''' - -all_properties_yaml = ''' ---- -flags: - flag1: - key: flag1 - "on": true -flagValues: - flag2: value2 -segments: - seg1: - key: seg1 - include: ["user1"] -''' - -flag_only_json = ''' - { - "flags": { - "flag1": { - "key": "flag1", - "on": true, - "fallthrough": { - "variation": 2 - }, - "variations": [ "fall", "off", "on" ] - } - } - } -''' - -segment_only_json = ''' - { - "segments": { - "seg1": { - "key": "seg1", - "include": ["user1"] - } - } - } -''' - -data_source = None -store = None -ready = None - - -def setup_function(): - global data_source, store, ready - store = InMemoryFeatureStore() - ready = threading.Event() - - -def teardown_function(): - if data_source is not None: - data_source.stop() - - -def make_data_source(config, **kwargs): - global data_source - data_source = Files.new_data_source(**kwargs)(with_update_sink(config, store), store, ready) - return data_source - - -def make_temp_file(content): - f, path = tempfile.mkstemp() - os.write(f, content.encode("latin-1")) - os.close(f) - return path - - -def replace_file(path, content): - with open(path, 'w') as f: - f.write(content) - - -def test_does_not_load_data_prior_to_start(): - path = make_temp_file('{"flagValues":{"key":"value"}}') - try: - source = make_data_source(Config("SDK_KEY"), paths=path) - assert ready.is_set() is False - assert source.initialized() is False - assert store.initialized is False - finally: - os.remove(path) - - -def test_loads_flags_on_start_from_json(): - path = make_temp_file(all_properties_json) - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - try: - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - source = make_data_source(config, paths=path) - source.start() - assert store.initialized is True - assert sorted(list(store.all(FEATURES, lambda x: x).keys())) == all_flag_keys - - assert len(spy.statuses) == 1 - assert spy.statuses[0].state == DataSourceState.VALID - assert spy.statuses[0].error is None - finally: - os.remove(path) - - -def test_handles_invalid_format_correctly(): - path = make_temp_file('{"flagValues":{') - spy = SpyListener() - listeners = Listeners() - listeners.add(spy) - - try: - config = Config("SDK_KEY") - config._data_source_update_sink = DataSourceUpdateSinkImpl(store, listeners, Listeners()) - source = make_data_source(config, paths=path) - source.start() - assert store.initialized is False - - assert len(spy.statuses) == 1 - assert spy.statuses[0].state == DataSourceState.INITIALIZING - assert spy.statuses[0].error.kind == DataSourceErrorKind.INVALID_DATA - finally: - os.remove(path) - - -def test_loads_flags_on_start_from_yaml(): - if not have_yaml: - pytest.skip("skipping file source test with YAML because pyyaml isn't available") - path = make_temp_file(all_properties_yaml) - try: - source = make_data_source(Config("SDK_KEY"), paths=path) - source.start() - assert store.initialized is True - assert sorted(list(store.all(FEATURES, lambda x: x).keys())) == all_flag_keys - finally: - os.remove(path) - - -def test_sets_ready_event_and_initialized_on_successful_load(): - path = make_temp_file(all_properties_json) - try: - source = make_data_source(Config("SDK_KEY"), paths=path) - source.start() - assert source.initialized() is True - assert ready.is_set() is True - finally: - os.remove(path) - - -def test_sets_ready_event_and_does_not_set_initialized_on_unsuccessful_load(): - bad_file_path = 'no-such-file' - source = make_data_source(Config("SDK_KEY"), paths=bad_file_path) - source.start() - assert source.initialized() is False - assert ready.is_set() is True - - -def test_can_load_multiple_files(): - path1 = make_temp_file(flag_only_json) - path2 = make_temp_file(segment_only_json) - try: - source = make_data_source(Config("SDK_KEY"), paths=[path1, path2]) - source.start() - assert len(store.all(FEATURES, lambda x: x)) == 1 - assert len(store.all(SEGMENTS, lambda x: x)) == 1 - finally: - os.remove(path1) - os.remove(path2) - - -def test_does_not_allow_duplicate_keys(): - path1 = make_temp_file(flag_only_json) - path2 = make_temp_file(flag_only_json) - try: - source = make_data_source(Config("SDK_KEY"), paths=[path1, path2]) - source.start() - assert len(store.all(FEATURES, lambda x: x)) == 0 - finally: - os.remove(path1) - os.remove(path2) - - -def test_does_not_reload_modified_file_if_auto_update_is_off(): - path = make_temp_file(flag_only_json) - try: - source = make_data_source(Config("SDK_KEY"), paths=path) - source.start() - assert len(store.all(SEGMENTS, lambda x: x)) == 0 - time.sleep(0.5) - replace_file(path, segment_only_json) - time.sleep(0.5) - assert len(store.all(SEGMENTS, lambda x: x)) == 0 - finally: - os.remove(path) - - -def do_auto_update_test(options): - path = make_temp_file(flag_only_json) - options['paths'] = path - try: - source = make_data_source(Config("SDK_KEY"), **options) - source.start() - assert len(store.all(SEGMENTS, lambda x: x)) == 0 - time.sleep(0.5) - replace_file(path, segment_only_json) - deadline = time.time() + 20 - while time.time() < deadline: - time.sleep(0.1) - if len(store.all(SEGMENTS, lambda x: x)) == 1: - return - assert False, "Flags were not reloaded after 20 seconds" - finally: - os.remove(path) - - -def test_reloads_modified_file_if_auto_update_is_on(): - do_auto_update_test({'auto_update': True}) - - -def test_reloads_modified_file_in_polling_mode(): - do_auto_update_test({'auto_update': True, 'force_polling': True, 'poll_interval': 0.1}) - - -def test_evaluates_full_flag_with_client_as_expected(): - path = make_temp_file(all_properties_json) - try: - factory = Files.new_data_source(paths=path) - client = LDClient(config=Config('SDK_KEY', update_processor_class=factory, send_events=False)) - value = client.variation('flag1', Context.from_dict({'key': 'user', 'kind': 'user'}), '') - assert value == 'on' - finally: - os.remove(path) - if client is not None: - client.close() - - -def test_evaluates_simplified_flag_with_client_as_expected(): - path = make_temp_file(all_properties_json) - try: - factory = Files.new_data_source(paths=path) - client = LDClient(config=Config('SDK_KEY', update_processor_class=factory, send_events=False)) - value = client.variation('flag2', Context.from_dict({'key': 'user', 'kind': 'user'}), '') - assert value == 'value2' - finally: - os.remove(path) - if client is not None: - client.close() - - -unsafe_yaml_caused_method_to_be_called = False - - -def arbitrary_method_called_from_yaml(x): - global unsafe_yaml_caused_method_to_be_called - unsafe_yaml_caused_method_to_be_called = True - - -def test_does_not_allow_unsafe_yaml(): - if not have_yaml: - pytest.skip("skipping file source test with YAML because pyyaml isn't available") - - # This extended syntax defined by pyyaml allows arbitrary code execution. We should be using - # yaml.safe_load() which does not support such things. - unsafe_yaml = ''' -!!python/object/apply:ldclient.testing.test_file_data_source.arbitrary_method_called_from_yaml ["hi"] -''' - path = make_temp_file(unsafe_yaml) - try: - factory = Files.new_data_source(paths=path) - client = LDClient(config=Config('SDK_KEY', update_processor_class=factory, send_events=False)) - finally: - os.remove(path) - if client is not None: - client.close() - assert unsafe_yaml_caused_method_to_be_called is False - - -def test_constructor_raises_without_update_sink(): - with pytest.raises(ValueError, match="data_source_update_sink"): - Files.new_data_source(paths=[])(Config("SDK_KEY"), store, ready) diff --git a/ldclient/testing/test_init.py b/ldclient/testing/test_init.py index c70d04f1..d8cbcbbf 100644 --- a/ldclient/testing/test_init.py +++ b/ldclient/testing/test_init.py @@ -11,8 +11,8 @@ def test_set_config(): old_sdk_key = "OLD_SDK_KEY" new_sdk_key = "NEW_SDK_KEY" - old_config = Config(sdk_key=old_sdk_key, stream=False, offline=True) - new_config = Config(sdk_key=new_sdk_key, stream=False, offline=True) + old_config = Config(sdk_key=old_sdk_key, offline=True) + new_config = Config(sdk_key=new_sdk_key, offline=True) ldclient.set_config(old_config) old_client = ldclient.get() diff --git a/ldclient/testing/test_ldclient.py b/ldclient/testing/test_ldclient.py index bec5fa85..67af1414 100644 --- a/ldclient/testing/test_ldclient.py +++ b/ldclient/testing/test_ldclient.py @@ -1,13 +1,18 @@ +import logging + import pytest from ldclient import datasystem from ldclient.client import Config, Context, LDClient from ldclient.datasystem import DataStoreMode from ldclient.feature_store import InMemoryFeatureStore -from ldclient.impl.datasource.polling import PollingUpdateProcessor -from ldclient.impl.datasource.streaming import StreamingUpdateProcessor -from ldclient.impl.stubs import NullUpdateProcessor +from ldclient.impl.datasourcev2.polling import ( + FallbackToFDv1PollingDataSourceBuilder, + PollingDataSourceBuilder +) +from ldclient.impl.datasourcev2.streaming import StreamingDataSourceBuilder from ldclient.impl.util import _Success +from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.interfaces import ( Basis, BasisResult, @@ -50,8 +55,26 @@ def make_offline_client(): return LDClient(config=Config(sdk_key="secret", offline=True, base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri)) -def make_ldd_client(): - return LDClient(config=Config(sdk_key="secret", datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build(), base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri)) +def make_daemon_client(store=None, **kwargs): + config = Config( + sdk_key="secret", + datasystem_config=datasystem.daemon(store or InMemoryFeatureStore()).build(), + base_uri=unreachable_uri, + events_uri=unreachable_uri, + stream_uri=unreachable_uri, + diagnostic_opt_out=True, + **kwargs, + ) + return LDClient(config=config) + + +class _ClosableStore(InMemoryFeatureStore): + def __init__(self): + super().__init__() + self.closed = False + + def close(self): + self.closed = True def get_first_event(c): @@ -66,27 +89,70 @@ def count_events(c): return n -def test_client_has_null_update_processor_in_offline_mode(): - with make_offline_client() as client: - assert isinstance(client._data_system._update_processor, NullUpdateProcessor) +def test_client_uses_the_default_data_system_when_none_is_set(): + config = Config(sdk_key="secret", base_uri=unreachable_uri, stream_uri=unreachable_uri, send_events=False) + with LDClient(config=config, start_wait=0) as client: + dsc = client._datasystem_config + assert [type(b) for b in dsc.initializers] == [PollingDataSourceBuilder] + assert [type(b) for b in dsc.synchronizers] == [StreamingDataSourceBuilder, PollingDataSourceBuilder] + assert isinstance(dsc.fdv1_fallback_synchronizer, FallbackToFDv1PollingDataSourceBuilder) + assert dsc.data_store is None -def test_client_has_null_update_processor_in_ldd_mode(): - config = Config(sdk_key="secret", use_ldd=True, base_uri=unreachable_uri, events_uri=unreachable_uri, stream_uri=unreachable_uri) - with LDClient(config=config) as client: - assert isinstance(client._data_system._update_processor, NullUpdateProcessor) +def test_client_uses_the_configured_data_system(): + dsc = datasystem.polling().build() + config = Config(sdk_key="secret", base_uri=unreachable_uri, send_events=False, datasystem_config=dsc) + with LDClient(config=config, start_wait=0) as client: + assert client._datasystem_config is dsc -def test_client_has_streaming_processor_by_default(): - config = Config(sdk_key="secret", base_uri=unreachable_uri, stream_uri=unreachable_uri, send_events=False) - with LDClient(config=config, start_wait=0) as client: - assert isinstance(client._data_system._update_processor, StreamingUpdateProcessor) +def test_daemon_mode_client_is_initialized_with_an_empty_store(): + with make_daemon_client(send_events=False) as client: + assert client.is_initialized() -def test_client_has_polling_processor_if_streaming_is_disabled(): - config = Config(sdk_key="secret", stream=False, base_uri=unreachable_uri, stream_uri=unreachable_uri, send_events=False) - with LDClient(config=config, start_wait=0) as client: - assert isinstance(client._data_system._update_processor, PollingUpdateProcessor) +def test_daemon_mode_logs_daemon_mode(caplog): + caplog.set_level(logging.INFO) + with make_daemon_client(send_events=False): + pass + assert "Started LaunchDarkly Client in daemon mode" in caplog.text + + +def test_offline_mode_with_a_daemon_config_logs_only_offline_mode(caplog): + caplog.set_level(logging.INFO) + with make_daemon_client(send_events=False, offline=True): + pass + assert "Started LaunchDarkly Client in offline mode" in caplog.text + assert "daemon mode" not in caplog.text + + +def test_data_system_with_no_sources_and_no_store_logs_a_warning(caplog): + config = Config(sdk_key="secret", send_events=False, datasystem_config=datasystem.custom().build()) + with LDClient(config=config, start_wait=0): + pass + assert "daemon mode" not in caplog.text + assert any( + r.levelname == "WARNING" and "no data sources and no persistent store" in r.message + for r in caplog.records + ) + + +def test_close_closes_the_persistent_store_in_daemon_mode(): + store = _ClosableStore() + client = make_daemon_client(store, send_events=False) + client.close() + assert store.closed + + +def test_close_closes_the_persistent_store_with_a_synchronizer(): + store = _ClosableStore() + dsc = datasystem.custom() \ + .synchronizers(TestDataV2.data_source().builder) \ + .data_store(store, DataStoreMode.READ_WRITE) \ + .build() + client = LDClient(config=Config(sdk_key="secret", send_events=False, datasystem_config=dsc)) + client.close() + assert store.closed def test_toggle_offline(): diff --git a/ldclient/testing/test_ldclient_end_to_end.py b/ldclient/testing/test_ldclient_end_to_end.py deleted file mode 100644 index f5b5b9b0..00000000 --- a/ldclient/testing/test_ldclient_end_to_end.py +++ /dev/null @@ -1,213 +0,0 @@ -import json -import sys -import time - -import pytest - -from ldclient.client import Context, LDClient -from ldclient.config import Config, HTTPConfig -from ldclient.hook import EvaluationSeriesContext, Hook, Metadata -from ldclient.testing.http_util import ( - BasicResponse, - SequentialHandler, - start_secure_server, - start_server -) -from ldclient.testing.stub_util import ( - make_put_event, - poll_content, - stream_content -) - -sdk_key = 'sdk-key' -user = Context.from_dict({'key': 'userkey', 'kind': 'user'}) -always_true_flag = {'key': 'flagkey', 'version': 1, 'on': False, 'offVariation': 1, 'variations': [False, True]} - - -def test_config_ignores_initial_instance_id(): - with start_server() as stream_server: - with stream_content(make_put_event([always_true_flag])) as stream_handler: - stream_server.for_path('/all', stream_handler) - config = Config(sdk_key=sdk_key, stream_uri=stream_server.uri, send_events=False) - config._instance_id = "Hey, I'm not supposed to modify this" - - with LDClient(config=config) as client: - assert client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is True - - r = stream_server.await_request() - assert r.headers['X-LaunchDarkly-Instance-Id'] == config._instance_id - assert r.headers['X-LaunchDarkly-Instance-Id'] != "Hey, I'm not supposed to modify this" - - -def test_client_starts_in_streaming_mode(): - with start_server() as stream_server: - with stream_content(make_put_event([always_true_flag])) as stream_handler: - stream_server.for_path('/all', stream_handler) - config = Config(sdk_key=sdk_key, stream_uri=stream_server.uri, send_events=False) - - with LDClient(config=config) as client: - assert client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is True - - r = stream_server.await_request() - assert r.headers['Authorization'] == sdk_key - - -def test_client_does_not_initialize_in_streaming_mode_with_401_error(): - """A rejected SDK key no longer fails fast. The constructor waits out the - full start_wait and returns uninitialized, while the SDK keeps retrying in - the background.""" - with start_server() as stream_server: - stream_server.for_path('/all', BasicResponse(401)) - config = Config(sdk_key=sdk_key, stream_uri=stream_server.uri, send_events=False) - - start_wait = 0.5 - started = time.monotonic() - with LDClient(config=config, start_wait=start_wait) as client: - elapsed = time.monotonic() - started - # A bound rather than the exact start_wait: Event.wait can return a - # fraction early against a separate clock. Failing fast took - # milliseconds, so this still catches it. - assert elapsed >= start_wait / 2 - assert not client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is False - - -def test_client_retries_connection_in_streaming_mode_with_non_fatal_error(): - with start_server() as stream_server: - with stream_content(make_put_event([always_true_flag])) as stream_handler: - error_then_success = SequentialHandler(BasicResponse(503), stream_handler) - stream_server.for_path('/all', error_then_success) - config = Config(sdk_key=sdk_key, stream_uri=stream_server.uri, initial_reconnect_delay=0.001, send_events=False) - - with LDClient(config=config) as client: - assert client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is True - - r = stream_server.await_request() - assert r.headers['Authorization'] == sdk_key - - -def test_client_starts_in_polling_mode(): - with start_server() as poll_server: - poll_server.for_path('/sdk/latest-all', poll_content([always_true_flag])) - config = Config(sdk_key=sdk_key, base_uri=poll_server.uri, stream=False, send_events=False) - - with LDClient(config=config) as client: - assert client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is True - - r = poll_server.await_request() - assert r.headers['Authorization'] == sdk_key - - -def test_client_does_not_initialize_in_polling_mode_with_401_error(): - """As with streaming, a rejected SDK key no longer fails fast.""" - with start_server() as poll_server: - poll_server.for_path('/sdk/latest-all', BasicResponse(401)) - config = Config(sdk_key=sdk_key, base_uri=poll_server.uri, stream=False, send_events=False) - - start_wait = 0.5 - started = time.monotonic() - with LDClient(config=config, start_wait=start_wait) as client: - elapsed = time.monotonic() - started - # See the streaming case above: a bound, not the exact start_wait. - assert elapsed >= start_wait / 2 - assert not client.is_initialized() - assert client.variation(always_true_flag['key'], user, False) is False - - -def test_client_sends_event_without_diagnostics(): - with start_server() as poll_server: - with start_server() as events_server: - poll_server.for_path('/sdk/latest-all', poll_content([always_true_flag])) - events_server.for_path('/bulk', BasicResponse(202)) - - config = Config(sdk_key=sdk_key, base_uri=poll_server.uri, events_uri=events_server.uri, stream=False, diagnostic_opt_out=True) - with LDClient(config=config) as client: - assert client.is_initialized() - client.identify(user) - client.flush() - - r = events_server.await_request() - assert r.headers['Authorization'] == sdk_key - data = json.loads(r.body) - assert len(data) == 1 - assert data[0]['kind'] == 'identify' - - -def test_client_sends_diagnostics(): - with start_server() as poll_server: - with start_server() as events_server: - poll_server.for_path('/sdk/latest-all', poll_content([always_true_flag])) - events_server.for_path('/diagnostic', BasicResponse(202)) - - config = Config(sdk_key=sdk_key, base_uri=poll_server.uri, events_uri=events_server.uri, stream=False) - with LDClient(config=config) as client: - assert client.is_initialized() - - r = events_server.await_request() - assert r.headers['Authorization'] == sdk_key - data = json.loads(r.body) - assert data['kind'] == 'diagnostic-init' - - -def test_cannot_connect_with_selfsigned_cert_by_default(): - with start_secure_server() as server: - server.for_path('/sdk/latest-all', poll_content()) - config = Config(sdk_key='sdk_key', base_uri=server.uri, stream=False, send_events=False) - with LDClient(config=config, start_wait=1.5) as client: - assert not client.is_initialized() - - -def test_can_connect_with_selfsigned_cert_if_ssl_verify_is_false(): - with start_secure_server() as server: - server.for_path('/sdk/latest-all', poll_content()) - config = Config(sdk_key='sdk_key', base_uri=server.uri, stream=False, send_events=False, http=HTTPConfig(disable_ssl_verification=True)) - with LDClient(config=config) as client: - assert client.is_initialized() - - -def test_can_connect_with_selfsigned_cert_if_disable_ssl_verification_is_true(): - with start_secure_server() as server: - server.for_path('/sdk/latest-all', poll_content()) - config = Config(sdk_key='sdk_key', base_uri=server.uri, stream=False, send_events=False, http=HTTPConfig(disable_ssl_verification=True)) - with LDClient(config=config) as client: - assert client.is_initialized() - - -def test_can_connect_with_selfsigned_cert_by_setting_ca_certs(): - with start_secure_server() as server: - server.for_path('/sdk/latest-all', poll_content()) - config = Config(sdk_key='sdk_key', base_uri=server.uri, stream=False, send_events=False, http=HTTPConfig(ca_certs='./ldclient/testing/selfsigned.pem')) - with LDClient(config=config) as client: - assert client.is_initialized() - - -def test_hooks_receive_environment_id_in_streaming_mode(): - contexts = [] - - class CapturingHook(Hook): - @property - def metadata(self) -> Metadata: - return Metadata(name='capturing-hook') - - def before_evaluation(self, series_context: EvaluationSeriesContext, data: dict) -> dict: - contexts.append(series_context) - return data - - def after_evaluation(self, series_context: EvaluationSeriesContext, data: dict, detail) -> dict: - return data - - with start_server() as stream_server: - with stream_content(make_put_event([always_true_flag]), headers={'X-LD-EnvID': 'env-abc-123'}) as stream_handler: - stream_server.for_path('/all', stream_handler) - config = Config(sdk_key=sdk_key, stream_uri=stream_server.uri, send_events=False, hooks=[CapturingHook()]) - - with LDClient(config=config) as client: - assert client.is_initialized() - client.variation(always_true_flag['key'], user, False) - - assert len(contexts) == 1 - assert contexts[0].environment_id == 'env-abc-123' diff --git a/ldclient/testing/test_ldclient_end_to_end_fdv2.py b/ldclient/testing/test_ldclient_end_to_end_fdv2.py index 335ddd59..ac8f25ab 100644 --- a/ldclient/testing/test_ldclient_end_to_end_fdv2.py +++ b/ldclient/testing/test_ldclient_end_to_end_fdv2.py @@ -14,6 +14,7 @@ from ldclient.client import Context, LDClient from ldclient.config import Config, HTTPConfig from ldclient.feature_store import InMemoryFeatureStore +from ldclient.hook import EvaluationSeriesContext, Hook, Metadata from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.testing.http_util import ( BasicResponse, @@ -58,9 +59,9 @@ def poll_response(flags): return JsonResponse({'events': fdv2_events(flags)}) -def stream_response(flags): +def stream_response(flags, headers=None): """Return an open SSE stream that sends a full transfer of the given flags.""" - stream = ChunkedResponse({'Content-Type': 'text/event-stream'}) + stream = ChunkedResponse({'Content-Type': 'text/event-stream', **(headers or {})}) for e in fdv2_events(flags): stream.push('event: %s\ndata: %s\n\n' % (e['event'], json.dumps(e['data']))) return stream @@ -91,6 +92,86 @@ def test_client_starts_in_streaming_mode(): assert r.headers['Authorization'] == sdk_key +def test_config_ignores_initial_instance_id(): + with start_server() as server: + with stream_response([always_true_flag]) as stream: + server.for_path('/sdk/stream', stream) + config = make_config(server.uri, datasystem.streaming()) + config._instance_id = "Hey, I'm not supposed to modify this" + + with LDClient(config=config) as client: + assert client.is_initialized() + + r = server.await_request() + assert r.headers['X-LaunchDarkly-Instance-Id'] == config._instance_id + assert r.headers['X-LaunchDarkly-Instance-Id'] != "Hey, I'm not supposed to modify this" + + +def test_client_sends_event_without_diagnostics(): + with start_server() as server: + with start_server() as events_server: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + events_server.for_path('/bulk', BasicResponse(202)) + config = Config(sdk_key, base_uri=server.uri, events_uri=events_server.uri, diagnostic_opt_out=True, + datasystem_config=datasystem.polling().build()) + + with LDClient(config=config) as client: + assert client.is_initialized() + client.identify(user) + client.flush() + + r = events_server.await_request() + assert r.headers['Authorization'] == sdk_key + data = json.loads(r.body) + assert len(data) == 1 + assert data[0]['kind'] == 'identify' + + +def test_client_sends_diagnostics(): + with start_server() as server: + with start_server() as events_server: + server.for_path('/sdk/poll', poll_response([always_true_flag])) + events_server.for_path('/diagnostic', BasicResponse(202)) + config = Config(sdk_key, base_uri=server.uri, events_uri=events_server.uri, + datasystem_config=datasystem.polling().build()) + + with LDClient(config=config) as client: + assert client.is_initialized() + + r = events_server.await_request() + assert r.headers['Authorization'] == sdk_key + data = json.loads(r.body) + assert data['kind'] == 'diagnostic-init' + + +def test_hooks_receive_environment_id_in_streaming_mode(): + contexts = [] + + class CapturingHook(Hook): + @property + def metadata(self) -> Metadata: + return Metadata(name='capturing-hook') + + def before_evaluation(self, series_context: EvaluationSeriesContext, data: dict) -> dict: + contexts.append(series_context) + return data + + def after_evaluation(self, series_context: EvaluationSeriesContext, data: dict, detail) -> dict: + return data + + with start_server() as server: + with stream_response([always_true_flag], headers={'X-LD-EnvID': 'env-abc-123'}) as stream: + server.for_path('/sdk/stream', stream) + config = make_config(server.uri, datasystem.streaming(), hooks=[CapturingHook()]) + + with LDClient(config=config) as client: + assert client.is_initialized() + client.variation(always_true_flag['key'], user, False) + + assert len(contexts) == 1 + assert contexts[0].environment_id == 'env-abc-123' + + def test_client_starts_in_polling_mode(): with start_server() as server: server.for_path('/sdk/poll', poll_response([always_true_flag])) diff --git a/ldclient/testing/test_ldclient_evaluation.py b/ldclient/testing/test_ldclient_evaluation.py index 059cc613..c68c1377 100644 --- a/ldclient/testing/test_ldclient_evaluation.py +++ b/ldclient/testing/test_ldclient_evaluation.py @@ -1,5 +1,6 @@ import logging import time +from threading import Event from ldclient import datasystem from ldclient.client import Config, Context, LDClient @@ -8,7 +9,7 @@ from ldclient.feature_store import InMemoryFeatureStore from ldclient.impl.big_segments import _hash_for_user_key from ldclient.impl.evaluator import _make_big_segment_ref -from ldclient.interfaces import FeatureStore +from ldclient.interfaces import DataStoreMode, FeatureStore from ldclient.testing.builders import * from ldclient.testing.mock_components import MockBigSegmentStore from ldclient.testing.stub_util import MockEventProcessor @@ -447,9 +448,31 @@ def fake_evaluate(flag, context, event_factory): assert 'prerequisites' not in metadata['bad-last'] -def make_client_with_cached_data(store): - # Daemon mode never receives data from a data source, so the client serves - # cached values from the store. +class _SilentSynchronizer: + """A synchronizer that sends no data until it stops.""" + + def __init__(self): + self._stopped = Event() + + @property + def name(self) -> str: + return 'silent' + + def sync(self, ss): + self._stopped.wait() + return + yield + + def stop(self): + self._stopped.set() + + +class _SilentSynchronizerBuilder: + def build(self, config): + return _SilentSynchronizer() + + +def make_client_with_data_system(datasystem_config): return LDClient( config=Config( sdk_key='SDK_KEY', @@ -457,11 +480,23 @@ def make_client_with_cached_data(store): events_uri=unreachable_uri, stream_uri=unreachable_uri, event_processor_class=MockEventProcessor, - datasystem_config=datasystem.daemon(store).build(), - ) + datasystem_config=datasystem_config, + ), + start_wait=0, ) +def make_client_with_cached_data(store): + # The data source never sends data, so the client serves cached values from the store. + dsc = datasystem.custom().synchronizers(_SilentSynchronizerBuilder()).data_store(store, DataStoreMode.READ_ONLY).build() + return make_client_with_data_system(dsc) + + +def evaluation_warnings(caplog): + warnings = get_log_lines(caplog, 'WARNING') + return [m for m in warnings if m.startswith('Feature Flag evaluation attempted') or m.startswith('all_flags_state() called before')] + + def test_cached_data_warnings_are_logged_once_per_client(caplog): caplog.set_level(logging.WARNING, logger='ldclient.util') store = InMemoryFeatureStore() @@ -480,3 +515,15 @@ def test_cached_data_warnings_are_logged_once_per_client(caplog): assert len(all_flags_warnings) == 1 assert eval_warnings[0].endswith('This message is logged once.') assert all_flags_warnings[0].endswith('This message is logged once.') + client.close() + + +def test_daemon_mode_does_not_log_cached_data_warnings(caplog): + caplog.set_level(logging.WARNING, logger='ldclient.util') + store = InMemoryFeatureStore() + store.init({FEATURES: {'key1': flag1}}) + with make_client_with_data_system(datasystem.daemon(store).build()) as client: + assert client.variation('key1', user, default='default') == 'value1' + assert client.all_flags_state(user).valid + + assert evaluation_warnings(caplog) == [] diff --git a/ldclient/testing/test_ldclient_events.py b/ldclient/testing/test_ldclient_events.py index c78d7f72..bf07a102 100644 --- a/ldclient/testing/test_ldclient_events.py +++ b/ldclient/testing/test_ldclient_events.py @@ -15,7 +15,7 @@ from ldclient.testing.test_ldclient import ( context, make_client, - make_ldd_client, + make_daemon_client, make_offline_client, unreachable_uri, user @@ -46,8 +46,8 @@ def test_client_has_null_event_processor_if_send_events_off(): assert isinstance(client._event_processor, NullEventProcessor) -def test_client_has_normal_event_processor_in_ldd_mode(): - with make_ldd_client() as client: +def test_client_has_normal_event_processor_in_daemon_mode(): + with make_daemon_client() as client: assert isinstance(client._event_processor, DefaultEventProcessor) diff --git a/ldclient/testing/test_ldclient_fork.py b/ldclient/testing/test_ldclient_fork.py index 3f52860a..a019857d 100644 --- a/ldclient/testing/test_ldclient_fork.py +++ b/ldclient/testing/test_ldclient_fork.py @@ -15,9 +15,10 @@ from ldclient import datasystem from ldclient.client import Config, Context, LDClient +from ldclient.feature_store import InMemoryFeatureStore from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.migrations import Stage -from ldclient.testing.stub_util import MockEventProcessor, MockUpdateProcessor +from ldclient.testing.stub_util import MockEventProcessor unreachable_uri = "http://fake" @@ -43,9 +44,8 @@ def make_client(**kwargs) -> LDClient: return LDClient(config=make_config(**kwargs), start_wait=0) -def make_ldd_client(**kwargs) -> LDClient: - # The fork check keys on use_ldd, which only the FDv1 data system honors. - return make_client(use_ldd=True, datasystem_config=None, update_processor_class=MockUpdateProcessor, **kwargs) +def make_daemon_client(**kwargs) -> LDClient: + return make_client(datasystem_config=datasystem.daemon(InMemoryFeatureStore()).build(), **kwargs) def fork_warnings(caplog) -> list: @@ -185,8 +185,8 @@ def test_no_warning_in_offline_mode(caplog, monkeypatch): assert fork_warnings(caplog) == [] -def test_no_warning_in_ldd_mode_with_events_disabled(caplog, monkeypatch): - with make_ldd_client(send_events=False) as client: +def test_no_warning_in_daemon_mode_with_events_disabled(caplog, monkeypatch): + with make_daemon_client(send_events=False) as client: pretend_forked(monkeypatch) client.variation("flag", context, False) client.identify(context) @@ -194,8 +194,8 @@ def test_no_warning_in_ldd_mode_with_events_disabled(caplog, monkeypatch): assert fork_warnings(caplog) == [] -def test_warns_in_ldd_mode_with_events_enabled(caplog, monkeypatch): - with make_ldd_client(send_events=True) as client: +def test_warns_in_daemon_mode_with_events_enabled(caplog, monkeypatch): + with make_daemon_client(send_events=True) as client: pretend_forked(monkeypatch) client.variation("flag", context, False) assert len(fork_warnings(caplog)) == 1 diff --git a/ldclient/testing/test_ldclient_singleton.py b/ldclient/testing/test_ldclient_singleton.py index df8f6ed9..83e0a220 100644 --- a/ldclient/testing/test_ldclient_singleton.py +++ b/ldclient/testing/test_ldclient_singleton.py @@ -56,7 +56,6 @@ def test_set_sdk_key_after_init(): stream_server.for_path('/sdk/stream', stream_handler) - # copy_with_new_sdk_key drops datasystem_config, so the test builds a new config. ldclient.set_config(make_streaming_config(sdk_key, stream_server.uri)) wait_until(ldclient.get().is_initialized, timeout=30) diff --git a/ldclient/testing/test_util.py b/ldclient/testing/test_util.py index e52b1c77..fbfac15a 100644 --- a/ldclient/testing/test_util.py +++ b/ldclient/testing/test_util.py @@ -1,10 +1,7 @@ import os -from contextlib import contextmanager -from unittest import mock import pytest -from ldclient.impl import retry from ldclient.impl.util import redact_password skip_database_tests = os.environ.get('LD_SKIP_DATABASE_TESTS') == '1' @@ -28,69 +25,6 @@ def test_can_redact_password(password_redaction_tests): assert redact_password(input) == expected -class _FixedRandom: - """Stands in for the ``random`` module, always drawing the same value.""" - - def __init__(self, value: float): - self.value = value - - def random(self) -> float: - return self.value - - -class _TickingClock: - """Stands in for the ``time`` module, moving on with every read.""" - - def __init__(self, start: float, step: float): - self.now = start - self.step = step - - def monotonic(self) -> float: - self.now += self.step - return self.now - - -def record_healthy_windows(policy) -> list: - """Records the window each ``note_healthy`` call leaves in place, so a test - can tell one window from the next.""" - windows: list = [] - note = policy.note_healthy - - def wrapper(): - note() - windows.append(policy._healthy_since) - - policy.note_healthy = wrapper # type: ignore[method-assign] - return windows - - -@contextmanager -def ticking_clock(start: float = 1000.0, step: float = 1.0): - """Gives :mod:`ldclient.impl.retry` a clock that moves on every read, so a - timestamp it stored can be told apart from one it stored later.""" - with mock.patch.object(retry, 'time', _TickingClock(start, step)): - yield - - -@contextmanager -def fixed_retry_jitter(fraction: float): - """Fixes the jitter that :mod:`ldclient.impl.retry` subtracts from a delay. - - ``0`` subtracts none, so a test can assert an exact delay. A value just - below ``1`` subtracts as much as possible, which is half. - - Patching the retry module's own ``random`` reference keeps the change - local to that module; every other module keeps the real source. - """ - with mock.patch.object(retry, 'random', _FixedRandom(fraction)): - yield - - -def no_retry_jitter(): - """Removes the retry jitter, so a test can assert an exact delay.""" - return fixed_retry_jitter(0.0) - - class SpyListener: def __init__(self): self._statuses = []