diff --git a/contract-tests/async_service.py b/contract-tests/async_service.py index dae59b19..f818053d 100644 --- a/contract-tests/async_service.py +++ b/contract-tests/async_service.py @@ -62,6 +62,7 @@ async def handle_status(request: aiohttp.web.Request) -> aiohttp.web.Response: 'instance-id', 'anonymous-redaction', 'evaluation-hooks', + 'hook-environment-id', 'omit-anonymous-contexts', 'client-prereq-events', 'flag-change-listeners', diff --git a/ldclient/async_client.py b/ldclient/async_client.py index 9c9f975d..b8419418 100644 --- a/ldclient/async_client.py +++ b/ldclient/async_client.py @@ -735,7 +735,7 @@ async def __evaluate_with_hooks(self, key: str, context: Context, default_value: if not hooks: return await block() - series_context = EvaluationSeriesContext(key=key, context=context, default_value=default_value, method=method) + series_context = EvaluationSeriesContext(key=key, context=context, default_value=default_value, method=method, environment_id=self._data_system.environment_id) hook_data = self.__execute_before_evaluation(hooks, series_context) try: evaluation_result = await block() diff --git a/ldclient/impl/datasource/async_feature_requester.py b/ldclient/impl/datasource/async_feature_requester.py index 66a732d5..e41951a3 100644 --- a/ldclient/impl/datasource/async_feature_requester.py +++ b/ldclient/impl/datasource/async_feature_requester.py @@ -4,7 +4,7 @@ import json from collections import namedtuple -from typing import Optional +from typing import Mapping, Optional, Tuple from urllib import parse from ldclient.impl.aio.transport import AsyncHTTPTransport @@ -30,6 +30,10 @@ def __init__(self, config, transport: Optional[AsyncHTTPTransport] = None): self._poll_uri += '?%s' % parse.urlencode({'filter': config.payload_filter_key}) async def get_all_data(self): + (data, _) = await self.get_all_data_with_headers() + return data + + async def get_all_data_with_headers(self) -> Tuple[dict, Optional[Mapping[str, str]]]: uri = self._poll_uri hdrs = _headers(self._config, ASYNC_USER_AGENT) cache_entry = self._cache.get(uri) @@ -50,7 +54,7 @@ async def get_all_data(self): 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']} + return ({FEATURES: data['flags'], SEGMENTS: data['segments']}, r.headers) async def close(self): if self._owns_transport: diff --git a/ldclient/impl/datasource/async_polling.py b/ldclient/impl/datasource/async_polling.py index 5989c9ea..b7a1839e 100644 --- a/ldclient/impl/datasource/async_polling.py +++ b/ldclient/impl/datasource/async_polling.py @@ -5,11 +5,14 @@ # currently excluded from documentation - see docs/README.md import time -from typing import Optional +from typing import Any, Mapping, Optional, Protocol, Tuple, cast from ldclient.async_config import AsyncConfig from ldclient.impl.aio.concurrency import AsyncEvent, AsyncRepeatingTask -from ldclient.impl.datasource.datasource_common import async_sink_or_store +from ldclient.impl.datasource.datasource_common import ( + async_sink_or_store, + record_environment_id +) from ldclient.impl.retry import ( FailureKind, RetryState, @@ -31,6 +34,11 @@ ) +class _AsyncFeatureRequesterWithHeaders(Protocol): + async def get_all_data_with_headers(self) -> Tuple[Any, Optional[Mapping[str, str]]]: + ... + + class AsyncPollingUpdateProcessor(AsyncUpdateProcessor): """Polls LaunchDarkly for flag data on its own background task. @@ -69,10 +77,26 @@ async def stop(self): finally: await self._requester.close() + async 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. + """ + # TODO(v10): Unify this method with the sync version in polling.py. + # + # Look up the method on the class, not on the instance. On Python 3.10 + # and 3.11, isinstance with a runtime_checkable Protocol uses hasattr. + # Every mock instance passes that check. + if hasattr(self._requester.__class__, 'get_all_data_with_headers'): + return await cast(_AsyncFeatureRequesterWithHeaders, self._requester).get_all_data_with_headers() + + return (await self._requester.get_all_data(), None) + 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() + (all_data, headers) = await self._get_all_data_with_headers() + record_environment_id(self._data_source_update_sink, headers) await async_sink_or_store(self._data_source_update_sink, self._store).init(all_data) if self._data_source_update_sink is not None: diff --git a/ldclient/impl/datasource/async_status.py b/ldclient/impl/datasource/async_status.py index 29bccdb0..b09de88e 100644 --- a/ldclient/impl/datasource/async_status.py +++ b/ldclient/impl/datasource/async_status.py @@ -23,11 +23,19 @@ def __init__(self, store: AsyncFeatureStore, status_listeners: Listeners, flag_c self.__tracker = DependencyTracker() self.__status = DataSourceStatus(DataSourceState.INITIALIZING, time.time(), None) + self.__environment_id: Optional[str] = None @property def status(self) -> DataSourceStatus: return self.__status + @property + def environment_id(self) -> Optional[str]: + return self.__environment_id + + def set_environment_id(self, environment_id: str) -> None: + self.__environment_id = environment_id + async def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]) -> None: old_data: Optional[Dict[VersionedDataKind, Mapping[str, dict]]] = None diff --git a/ldclient/impl/datasource/async_streaming.py b/ldclient/impl/datasource/async_streaming.py index bc42ee0c..7ae9d500 100644 --- a/ldclient/impl/datasource/async_streaming.py +++ b/ldclient/impl/datasource/async_streaming.py @@ -19,7 +19,8 @@ STREAM_ALL_PATH, StreamClosedError, async_sink_or_store, - parse_path + parse_path, + record_environment_id ) from ldclient.impl.retry import ( FailureKind, @@ -92,6 +93,7 @@ async def _run(self): # 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) # On reconnect after an error the timer was cleared; reset it here. # For the initial connect the pre-loop stamp is already set. diff --git a/ldclient/impl/datasource/polling.py b/ldclient/impl/datasource/polling.py index 2eacc6ad..c68e7f5c 100644 --- a/ldclient/impl/datasource/polling.py +++ b/ldclient/impl/datasource/polling.py @@ -6,7 +6,7 @@ import time from threading import Event -from typing import Any, Mapping, Optional, Protocol, Tuple, runtime_checkable +from typing import Any, Mapping, Optional, Protocol, Tuple, cast from ldclient.config import Config from ldclient.impl.datasource.datasource_common import ( @@ -36,7 +36,6 @@ ) -@runtime_checkable class _FeatureRequesterWithHeaders(Protocol): def get_all_data_with_headers(self) -> Tuple[Any, Optional[Mapping[str, str]]]: ... @@ -120,7 +119,10 @@ 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() + # Look up the method on the class, not on the instance. On Python 3.10 + # and 3.11, isinstance with a runtime_checkable Protocol uses hasattr. + # Every mock instance passes that check. + if hasattr(self._requester.__class__, 'get_all_data_with_headers'): + return cast(_FeatureRequesterWithHeaders, self._requester).get_all_data_with_headers() return (self._requester.get_all_data(), None) diff --git a/ldclient/impl/datasystem/__init__.py b/ldclient/impl/datasystem/__init__.py index 6799351f..9dae7a93 100644 --- a/ldclient/impl/datasystem/__init__.py +++ b/ldclient/impl/datasystem/__init__.py @@ -244,6 +244,15 @@ def store(self) -> AsyncReadOnlyStore: """ raise NotImplementedError + @property + @abstractmethod + def environment_id(self) -> Optional[str]: + """ + Returns the environment ID reported by LaunchDarkly, if it is known. + See :attr:`DataSystem.environment_id`. + """ + raise NotImplementedError + @property @abstractmethod def override_layer(self) -> Optional["OverrideLayer"]: diff --git a/ldclient/impl/datasystem/async_fdv1.py b/ldclient/impl/datasystem/async_fdv1.py index a7bd1455..fef38c78 100644 --- a/ldclient/impl/datasystem/async_fdv1.py +++ b/ldclient/impl/datasystem/async_fdv1.py @@ -124,6 +124,10 @@ async def stop(self): def store(self) -> AsyncReadOnlyStore: return self._store_view + @property + def environment_id(self) -> Optional[str]: + return self._data_source_update_sink.environment_id + @property def override_layer(self) -> None: # Overrides are an option of the FDv2 data system only. diff --git a/ldclient/impl/datasystem/async_fdv2.py b/ldclient/impl/datasystem/async_fdv2.py index 899bbc48..e1a7d5bb 100644 --- a/ldclient/impl/datasystem/async_fdv2.py +++ b/ldclient/impl/datasystem/async_fdv2.py @@ -276,6 +276,8 @@ def __init__( wrapper = _AsyncFeatureStoreClientWrapper(data_system_config.data_store, self._data_store_status_provider.update_status) self._store.with_async_persistence(wrapper, writable, self._data_store_status_provider) + self._environment_id: Optional[str] = None + self._store_view = _AsyncReadOnlyStoreView(self._store) # Set only when an override source is configured. See the sync FDv2 for the roles of @@ -401,6 +403,12 @@ async def stop(self): # Close the store await self._store.close() + def _record_environment_id(self, environment_id: Optional[str]): + if not isinstance(environment_id, str) or environment_id == '': + return + + self._environment_id = environment_id + def _close_override_source(self, failure_message: str) -> None: # A custom source can raise from close. That is logged and not raised, so the rest of # the client still stops, or still starts after a failed start. @@ -499,6 +507,7 @@ async def _run_initializers(self, set_on_ready: AsyncEvent) -> bool: basis = basis_result.value log.info("Initialized via %s", initializer.name) + self._record_environment_id(basis.environment_id) # Apply the basis to the store await self._store.apply(basis.change_set, basis.persist) @@ -675,6 +684,9 @@ async def reader(): if self._stop_event.is_set(): return ConditionDirective.FALLBACK + if update.state == DataSourceState.VALID: + self._record_environment_id(update.environment_id) + # Handle the update if update.change_set is not None: await self._store.apply(update.change_set, True) @@ -713,6 +725,11 @@ async def reader(): # the synchronizer can't provide more updates, so we should remove it and fall back return ConditionDirective.REMOVE + @property + def environment_id(self) -> Optional[str]: + """Get the environment ID reported by LaunchDarkly, if known.""" + return self._environment_id + @property def store(self) -> AsyncReadOnlyStore: """ diff --git a/ldclient/testing/impl/datasource/test_async_polling.py b/ldclient/testing/impl/datasource/test_async_polling.py index 8d497ae0..953eb876 100644 --- a/ldclient/testing/impl/datasource/test_async_polling.py +++ b/ldclient/testing/impl/datasource/test_async_polling.py @@ -18,6 +18,8 @@ AsyncFeatureRequesterImpl ) from ldclient.impl.datasource.async_polling import AsyncPollingUpdateProcessor +from ldclient.impl.datasource.async_status import AsyncDataSourceUpdateSinkImpl +from ldclient.impl.listeners import Listeners from ldclient.impl.retry import ( POLLING_RESET_SUCCESSES, AfterConsecutiveSuccesses, @@ -83,8 +85,9 @@ def make_processor(config=None, store=None, ready=None, requester=None, retry_st if ready is None: ready = asyncio.Event() if requester is None: - requester = MagicMock() - requester.close = AsyncMock() + # The spec gives the mock the real requester class, so the processor + # sees get_all_data_with_headers and calls it. + requester = MagicMock(spec=AsyncFeatureRequesterImpl) return AsyncPollingUpdateProcessor( config=config, requester=requester, @@ -137,6 +140,19 @@ async def test_304_not_modified_returns_cached_data(self): headers = transport.request.call_args.kwargs['headers'] assert headers['If-None-Match'] == '"abc"' + @pytest.mark.asyncio + async def test_get_all_data_with_headers_returns_response_headers(self): + config = make_config() + transport = make_transport( + TransportResponse(200, {'X-LD-EnvID': 'env-abc-123'}, '{"flags": {}, "segments": {}}') + ) + requester = AsyncFeatureRequesterImpl(config, transport) + + (data, headers) = await requester.get_all_data_with_headers() + + assert data == {FEATURES: {}, SEGMENTS: {}} + assert headers.get('X-LD-EnvID') == 'env-abc-123' + @pytest.mark.asyncio async def test_etag_and_data_stored_after_successful_response(self): config = make_config() @@ -202,7 +218,7 @@ async def test_successful_poll_initializes_store_and_sets_ready(self, mock_inter config = make_config() processor = make_processor(config=config, store=store, ready=ready) - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) + processor._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) processor.start() await asyncio.wait_for(ready.wait(), timeout=2.0) @@ -226,7 +242,7 @@ async def test_unexpected_http_error_keeps_polling_and_leaves_ready_unset(self, 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._requester.get_all_data_with_headers = mock_requester processor.start() await asyncio.sleep(0.1) @@ -246,7 +262,7 @@ async def test_unexpected_http_error_moves_to_the_extended_regime(self, mock_int retry = fast_retry_state() processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=UnsuccessfulResponseException(401)) + processor._requester.get_all_data_with_headers = AsyncMock(side_effect=UnsuccessfulResponseException(401)) processor.start() await asyncio.sleep(0.05) @@ -267,11 +283,11 @@ async def test_the_first_success_after_an_outage_polls_at_the_cadence(self): 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)) + processor._requester.get_all_data_with_headers = 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) + processor._requester.get_all_data_with_headers = 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" @@ -292,14 +308,14 @@ async def test_recoverable_http_error_continues_polling(self, mock_interval): call_count = 0 - async def get_all_data(): + async def get_all_data_with_headers(): nonlocal call_count call_count += 1 if call_count < 3: raise UnsuccessfulResponseException(500) - return SAMPLE_DATA + return (SAMPLE_DATA, {}) - processor._requester.get_all_data = get_all_data + processor._requester.get_all_data_with_headers = get_all_data_with_headers processor.start() await asyncio.wait_for(ready.wait(), timeout=2.0) @@ -322,14 +338,14 @@ async def test_general_exception_does_not_stop_polling(self, mock_interval): call_count = 0 - async def get_all_data(): + async def get_all_data_with_headers(): nonlocal call_count call_count += 1 if call_count < 3: raise RuntimeError("transient error") - return SAMPLE_DATA + return (SAMPLE_DATA, {}) - processor._requester.get_all_data = get_all_data + processor._requester.get_all_data_with_headers = get_all_data_with_headers processor.start() @@ -357,10 +373,10 @@ async def test_general_exception_does_not_set_ready(self, mock_interval): config = make_config() processor = make_processor(config=config, store=store, ready=ready) - async def get_all_data(): + async def get_all_data_with_headers(): raise RuntimeError("transient error") - processor._requester.get_all_data = get_all_data + processor._requester.get_all_data_with_headers = get_all_data_with_headers processor.start() # Let several polls run; all raise. A transient error must not release @@ -390,7 +406,7 @@ async def test_transport_failures_poll_again_at_the_cadence(self, error): 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) + processor._requester.get_all_data_with_headers = AsyncMock(side_effect=error) await processor._fetch_and_store() assert retry.next_delay == 30 @@ -405,7 +421,7 @@ async def test_the_log_reports_the_growing_retry_delay(self, caplog): with no_retry_jitter(): retry = for_polling(30) processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock(side_effect=UnsuccessfulResponseException(401)) + processor._requester.get_all_data_with_headers = AsyncMock(side_effect=UnsuccessfulResponseException(401)) await processor._fetch_and_store() await processor._fetch_and_store() @@ -425,7 +441,7 @@ async def test_a_transport_error_reports_a_delay_and_keeps_its_stacktrace(self, 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")) + processor._requester.get_all_data_with_headers = AsyncMock(side_effect=ConnectionResetError(104, "reset by peer")) await processor._fetch_and_store() @@ -461,8 +477,8 @@ async def slow_poll(): async def close(): order.append('transport_closed') - requester = MagicMock() - requester.get_all_data = slow_poll + requester = MagicMock(spec=AsyncFeatureRequesterImpl) + requester.get_all_data_with_headers = slow_poll requester.close = close processor = make_processor(requester=requester) @@ -480,7 +496,7 @@ async def test_an_extended_regime_wait_is_cut_short_by_stop(self): task is waiting between polls.""" retry = fast_retry_state(ONE_HOUR) processor = make_processor(retry_state=retry) - processor._requester.get_all_data = AsyncMock( + processor._requester.get_all_data_with_headers = AsyncMock( side_effect=UnsuccessfulResponseException(401) ) @@ -511,7 +527,7 @@ async def slow_poll(): poll_count += 1 await asyncio.sleep(60) # Would block indefinitely without cancel - processor._requester.get_all_data = slow_poll + processor._requester.get_all_data_with_headers = slow_poll processor.start() await asyncio.sleep(0.05) # Let the task start @@ -538,7 +554,7 @@ async def test_unexpected_error_updates_sink_to_interrupted_never_off(self, mock 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( + processor._requester.get_all_data_with_headers = AsyncMock( side_effect=UnsuccessfulResponseException(403) ) @@ -566,7 +582,7 @@ async def test_stop_updates_sink_to_off(self, mock_interval): processor = make_processor(config=config) processor._data_source_update_sink = sink - processor._requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) + processor._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) processor.start() await processor.stop() @@ -590,7 +606,7 @@ async def test_a_poll_finishing_after_stop_reports_nothing(self): 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) + processor._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) await processor.stop() await processor._fetch_and_store() @@ -619,7 +635,7 @@ async def test_valid_status_is_reported_before_ready_is_set(self, mock_interval) 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._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) processor.start() await asyncio.wait_for(ready.wait(), timeout=2.0) @@ -651,7 +667,7 @@ async def _init_and_store(data): 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._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) processor.start() await asyncio.wait_for(ready.wait(), timeout=2.0) @@ -672,7 +688,7 @@ 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._requester.get_all_data_with_headers = AsyncMock(return_value=(SAMPLE_DATA, {})) processor.start() task = processor._task @@ -687,7 +703,7 @@ 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 = MagicMock(spec=AsyncFeatureRequesterImpl) requester.close = AsyncMock() processor = make_processor(requester=requester) @@ -707,3 +723,59 @@ async def hang(): await stop_task requester.close.assert_awaited_once() + + @pytest.mark.asyncio + async def test_mock_requester_with_only_get_all_data_initializes(self): + # On Python 3.10 and 3.11, every mock passed the runtime_checkable + # isinstance check. The processor then called a method that the test + # did not configure, and the store never initialized. + requester = MagicMock() + requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) + requester.close = AsyncMock() + + store = MockAsyncFeatureStore() + ready = asyncio.Event() + processor = make_processor(store=store, ready=ready, requester=requester) + + await processor._fetch_and_store() + + assert ready.is_set() + assert store.initialized + + @pytest.mark.asyncio + async def test_records_environment_id_from_polling_headers(self): + store = MockAsyncFeatureStore() + config = make_config() + sink = AsyncDataSourceUpdateSinkImpl(store, Listeners(), Listeners()) + config._data_source_update_sink = sink + + processor = make_processor(config=config, store=store) + processor._requester.get_all_data_with_headers = AsyncMock( + return_value=(SAMPLE_DATA, {'X-LD-EnvID': 'env-abc-123'}) + ) + + await processor._fetch_and_store() + + assert sink.environment_id == 'env-abc-123' + + @pytest.mark.asyncio + async def test_environment_id_is_none_when_requester_provides_no_headers(self): + # The spec has no get_all_data_with_headers, so the processor falls + # back to get_all_data and gets no headers. + requester = MagicMock(spec=['get_all_data', 'close']) + requester.get_all_data = AsyncMock(return_value=SAMPLE_DATA) + requester.close = AsyncMock() + + store = MockAsyncFeatureStore() + ready = asyncio.Event() + config = make_config() + sink = AsyncDataSourceUpdateSinkImpl(store, Listeners(), Listeners()) + config._data_source_update_sink = sink + + processor = make_processor(config=config, store=store, ready=ready, requester=requester) + + await processor._fetch_and_store() + + requester.get_all_data.assert_awaited_once() + assert ready.is_set() + assert sink.environment_id is None diff --git a/ldclient/testing/impl/datasource/test_async_streaming.py b/ldclient/testing/impl/datasource/test_async_streaming.py index 625fc468..b74496c3 100644 --- a/ldclient/testing/impl/datasource/test_async_streaming.py +++ b/ldclient/testing/impl/datasource/test_async_streaming.py @@ -18,9 +18,11 @@ from ldclient.config import Config from ldclient.impl.datasource import async_streaming +from ldclient.impl.datasource.async_status import AsyncDataSourceUpdateSinkImpl from ldclient.impl.datasource.async_streaming import ( AsyncStreamingUpdateProcessor ) +from ldclient.impl.listeners import Listeners from ldclient.impl.model import ModelEntity from ldclient.impl.retry import ( EXTENDED_CEILING_DELAY, @@ -924,6 +926,61 @@ async def close(): assert order.index(DataSourceState.OFF) < order.index('closed') +def _make_config_with_sink(): + store = MockAsyncFeatureStore() + config = _make_config() + sink = AsyncDataSourceUpdateSinkImpl(store, Listeners(), Listeners()) + config._data_source_update_sink = sink + return config, store, sink + + +@pytest.mark.asyncio +async def test_records_environment_id_from_stream_headers(): + config, store, sink = _make_config_with_sink() + actions = [_RealStart(headers={'X-LD-EnvID': 'env-abc-123'}), _event('put', _make_put_data())] + + proc, _, ready, _ = await _run_with_actions(actions, config=config, store=store) + + assert ready.is_set() + assert sink.environment_id == 'env-abc-123' + + await proc.stop() + + +@pytest.mark.asyncio +async def test_environment_id_is_none_when_not_provided(): + config, store, sink = _make_config_with_sink() + actions = [_start(), _event('put', _make_put_data())] + + proc, _, ready, _ = await _run_with_actions(actions, config=config, store=store) + + assert ready.is_set() + assert sink.environment_id is None + + await proc.stop() + + +@pytest.mark.asyncio +async def test_does_not_record_environment_id_from_error_response_headers(): + from ld_eventsource.errors import HTTPStatusError + + config, store, sink = _make_config_with_sink() + actions = [ + _fault(error=HTTPStatusError(503, {'X-LD-EnvID': 'env-from-error'})), + _start(), + _event('put', _make_put_data()), + ] + + proc, _, ready, _ = await _run_with_actions( + actions, config=config, store=store, retry_state=_fast_retry_state(), + ) + + assert ready.is_set() + assert sink.environment_id is None + + await proc.stop() + + def test_stream_init_duration_unaffected_by_wall_clock_step(monkeypatch): processor = object.__new__(AsyncStreamingUpdateProcessor) recorded = [] diff --git a/ldclient/testing/impl/datasource/test_polling_processor.py b/ldclient/testing/impl/datasource/test_polling_processor.py index 913438a4..14db6ef4 100644 --- a/ldclient/testing/impl/datasource/test_polling_processor.py +++ b/ldclient/testing/impl/datasource/test_polling_processor.py @@ -472,3 +472,18 @@ def test_environment_id_is_none_when_requester_provides_no_headers(): assert ready.wait(2) assert sink.environment_id is None + + +def test_mock_requester_with_only_get_all_data_initializes(): + # On Python 3.10 and 3.11, every mock passed the runtime_checkable + # isinstance check. The processor then called a method that the test + # did not configure, and the store never initialized. + requester = mock.MagicMock() + requester.get_all_data.return_value = {FEATURES: {}, SEGMENTS: {}} + + global pp + pp = PollingUpdateProcessor(Config("SDK_KEY"), requester, store, ready) + pp.start() + assert ready.wait(2) + + assert store.initialized diff --git a/ldclient/testing/impl/datasystem/test_async_fdv2.py b/ldclient/testing/impl/datasystem/test_async_fdv2.py index 73d032ac..dd7bea2a 100644 --- a/ldclient/testing/impl/datasystem/test_async_fdv2.py +++ b/ldclient/testing/impl/datasystem/test_async_fdv2.py @@ -18,7 +18,12 @@ AsyncFDv2, _AsyncFeatureStoreClientWrapper ) -from ldclient.impl.util import _LD_FD_FALLBACK_HEADER, _Fail, _Success +from ldclient.impl.util import ( + _LD_ENVID_HEADER, + _LD_FD_FALLBACK_HEADER, + _Fail, + _Success +) from ldclient.integrations.test_datav2 import TestDataV2 from ldclient.interfaces import ( AsyncFeatureStore, @@ -168,6 +173,74 @@ def _make_valid_update() -> Update: return Update(state=DataSourceState.VALID, change_set=change_set) +@pytest.mark.asyncio +async def test_environment_id_from_initializer_basis(): + builder = ChangeSetBuilder() + builder.start(IntentCode.TRANSFER_FULL) + change_set = builder.finish(Selector(state="initializer-state", version=1)) + initializer = MockAsyncInitializer( + _Success(value=Basis(change_set=change_set, persist=True, environment_id="env-from-initializer")), + ) + data_system = AsyncFDv2(AsyncConfig(sdk_key="dummy"), AsyncDataSystemConfig( + initializers=[MockAsyncInitializerBuilder(initializer)], + )) + assert data_system.environment_id is None + + ready = asyncio.Event() + data_system.start(ready) + try: + await asyncio.wait_for(ready.wait(), timeout=1) + assert data_system.environment_id == "env-from-initializer" + finally: + await data_system.stop() + + +@pytest.mark.asyncio +async def test_environment_id_is_not_recorded_from_initializer_error_headers(): + initializer = MockAsyncInitializer( + _Fail(error="boom", exception=None, headers={_LD_ENVID_HEADER: 'env-from-error'}), + ) + data_system = AsyncFDv2(AsyncConfig(sdk_key="dummy"), AsyncDataSystemConfig( + initializers=[MockAsyncInitializerBuilder(initializer)], + )) + + ready = asyncio.Event() + data_system.start(ready) + try: + await asyncio.wait_for(ready.wait(), timeout=1) + assert data_system.environment_id is None + finally: + await data_system.stop() + + +@pytest.mark.asyncio +async def test_environment_id_is_recorded_only_from_valid_updates(): + synchronizer = MockAsyncSynchronizer([ + Update(state=DataSourceState.VALID, environment_id="env-from-sync"), + # A later VALID update without an environment ID keeps the known one. + Update(state=DataSourceState.VALID, environment_id=None), + Update(state=DataSourceState.VALID, environment_id=""), + Update(state=DataSourceState.INTERRUPTED, environment_id="env-from-interrupted"), + ]) + data_system = AsyncFDv2(AsyncConfig(sdk_key="dummy"), AsyncDataSystemConfig( + synchronizers=[MockAsyncSynchronizerBuilder(synchronizer)], + )) + interrupted = asyncio.Event() + + def on_status(status: DataSourceStatus): + if status.state == DataSourceState.INTERRUPTED: + interrupted.set() + + data_system.data_source_status_provider.add_listener(on_status) + + data_system.start(asyncio.Event()) + try: + await asyncio.wait_for(interrupted.wait(), timeout=1) + assert data_system.environment_id == "env-from-sync" + finally: + await data_system.stop() + + @pytest.mark.asyncio async def test_async_fdv2_basic_start_stop(): td = TestDataV2.data_source() diff --git a/ldclient/testing/test_async_ldclient_end_to_end.py b/ldclient/testing/test_async_ldclient_end_to_end.py new file mode 100644 index 00000000..b7a3d5c3 --- /dev/null +++ b/ldclient/testing/test_async_ldclient_end_to_end.py @@ -0,0 +1,59 @@ +import pytest + +from ldclient.async_client import AsyncLDClient +from ldclient.async_config import AsyncConfig +from ldclient.hook import EvaluationSeriesContext, Hook, Metadata +from ldclient.testing.http_util import JsonResponse, start_server +from ldclient.testing.stub_util import make_put_event, stream_content +from ldclient.testing.test_ldclient_end_to_end import ( + always_true_flag, + sdk_key, + user +) + + +class CapturingHook(Hook): + def __init__(self): + self.contexts = [] + + @property + def metadata(self) -> Metadata: + return Metadata(name='capturing-hook') + + def before_evaluation(self, series_context: EvaluationSeriesContext, data: dict) -> dict: + self.contexts.append(series_context) + return data + + def after_evaluation(self, series_context: EvaluationSeriesContext, data: dict, detail) -> dict: + return data + + +@pytest.mark.asyncio +async def test_hooks_receive_environment_id_in_streaming_mode(): + hook = CapturingHook() + 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 = AsyncConfig(sdk_key=sdk_key, stream_uri=stream_server.uri, send_events=False, hooks=[hook]) + + async with AsyncLDClient(config) as client: + assert await client.is_initialized() + await client.variation(always_true_flag['key'], user, False) + + assert len(hook.contexts) == 1 + assert hook.contexts[0].environment_id == 'env-abc-123' + + +@pytest.mark.asyncio +async def test_hooks_receive_environment_id_in_polling_mode(): + hook = CapturingHook() + with start_server() as poll_server: + poll_server.for_path('/sdk/latest-all', JsonResponse({'flags': {always_true_flag['key']: always_true_flag}, 'segments': {}}, headers={'X-LD-EnvID': 'env-abc-123'})) + config = AsyncConfig(sdk_key=sdk_key, base_uri=poll_server.uri, stream=False, send_events=False, hooks=[hook]) + + async with AsyncLDClient(config) as client: + assert await client.is_initialized() + await client.variation(always_true_flag['key'], user, False) + + assert len(hook.contexts) == 1 + assert hook.contexts[0].environment_id == 'env-abc-123'