From 3d6bf039361c9a81c431cd6a11a8ba7adc34ecc5 Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Thu, 5 Nov 2026 13:17:20 -0500 Subject: [PATCH 1/2] fix: Apply the minimum poll interval to FDv2 polling data sources The FDv2 polling builders and the FDv1 fallback builders now raise a poll interval below 30 seconds to 30 seconds, as Config.poll_interval does. Before, an interval set on a builder could be any value. Also add FDv2 tests for behavior that only the FDv1 data system tested: - ETag and 304 handling, and SDK request headers, for the polling requesters and the streaming sources - the data source and data store status provider rules - flag change events through prerequisite and segment dependencies - stream init diagnostics on success and on failure --- ldclient/impl/datasourcev2/async_polling.py | 14 +- ldclient/impl/datasourcev2/polling.py | 14 +- .../test_poll_interval_minimum.py | 46 +++ .../impl/datasourcev2/test_requester_http.py | 230 ++++++++++++ .../test_stream_init_diagnostics.py | 342 ++++++++++++++++++ .../test_fdv2_flag_change_propagation.py | 292 +++++++++++++++ .../datasystem/test_fdv2_status_providers.py | 220 +++++++++++ 7 files changed, 1152 insertions(+), 6 deletions(-) create mode 100644 ldclient/testing/impl/datasourcev2/test_poll_interval_minimum.py create mode 100644 ldclient/testing/impl/datasourcev2/test_requester_http.py create mode 100644 ldclient/testing/impl/datasourcev2/test_stream_init_diagnostics.py create mode 100644 ldclient/testing/impl/datasystem/test_fdv2_flag_change_propagation.py create mode 100644 ldclient/testing/impl/datasystem/test_fdv2_status_providers.py diff --git a/ldclient/impl/datasourcev2/async_polling.py b/ldclient/impl/datasourcev2/async_polling.py index e3b6a3a3..6db18a69 100644 --- a/ldclient/impl/datasourcev2/async_polling.py +++ b/ldclient/impl/datasourcev2/async_polling.py @@ -10,6 +10,7 @@ from urllib import parse from ldclient.config import ( + DEFAULT_POLL_INTERVAL, DataSourceBuilder, DataSourceBuilderConfig, HTTPConfig @@ -264,7 +265,10 @@ def base_uri(self, uri: str) -> 'AsyncPollingDataSourceBuilder': return self def poll_interval(self, poll_interval: float) -> 'AsyncPollingDataSourceBuilder': - """Sets the polling interval for the AsyncPollingDataSource.""" + """ + Sets the polling interval, in seconds. An interval below 30 seconds is raised to 30 + seconds. + """ self.__poll_interval = poll_interval return self @@ -297,7 +301,8 @@ def build(self, config: DataSourceBuilderConfig) -> AsyncPollingDataSource: ) return AsyncPollingDataSource( - poll_interval=self.__poll_interval or config.poll_interval, + # The minimum also applies to an interval that is set on this builder. + poll_interval=max(self.__poll_interval or config.poll_interval, DEFAULT_POLL_INTERVAL), requester=requester ) @@ -319,7 +324,10 @@ def base_uri(self, uri: str) -> 'AsyncFallbackToFDv1PollingDataSourceBuilder': return self def poll_interval(self, poll_interval: float) -> 'AsyncFallbackToFDv1PollingDataSourceBuilder': - """Sets the polling interval for the data source.""" + """ + Sets the polling interval, in seconds. An interval below 30 seconds is raised to 30 + seconds. + """ self.__poll_interval = poll_interval return self diff --git a/ldclient/impl/datasourcev2/polling.py b/ldclient/impl/datasourcev2/polling.py index a96d5ed0..cd03a7b3 100644 --- a/ldclient/impl/datasourcev2/polling.py +++ b/ldclient/impl/datasourcev2/polling.py @@ -13,6 +13,7 @@ import urllib3 from ldclient.config import ( + DEFAULT_POLL_INTERVAL, DataSourceBuilder, DataSourceBuilderConfig, HTTPConfig @@ -240,7 +241,10 @@ def base_uri(self, uri: str) -> 'PollingDataSourceBuilder': return self def poll_interval(self, poll_interval: float) -> 'PollingDataSourceBuilder': - """Sets the polling interval for the PollingDataSource.""" + """ + Sets the polling interval, in seconds. An interval below 30 seconds is raised to 30 + seconds. + """ self.__poll_interval = poll_interval return self @@ -267,7 +271,8 @@ def build(self, config: DataSourceBuilderConfig) -> PollingDataSource: ) return PollingDataSource( - poll_interval=self.__poll_interval or config.poll_interval, + # The minimum also applies to an interval that is set on this builder. + poll_interval=max(self.__poll_interval or config.poll_interval, DEFAULT_POLL_INTERVAL), requester=requester ) @@ -288,7 +293,10 @@ def base_uri(self, uri: str) -> 'FallbackToFDv1PollingDataSourceBuilder': return self def poll_interval(self, poll_interval: float) -> 'FallbackToFDv1PollingDataSourceBuilder': - """Sets the polling interval for the data source.""" + """ + Sets the polling interval, in seconds. An interval below 30 seconds is raised to 30 + seconds. + """ self.__poll_interval = poll_interval return self diff --git a/ldclient/testing/impl/datasourcev2/test_poll_interval_minimum.py b/ldclient/testing/impl/datasourcev2/test_poll_interval_minimum.py new file mode 100644 index 00000000..b812c1b4 --- /dev/null +++ b/ldclient/testing/impl/datasourcev2/test_poll_interval_minimum.py @@ -0,0 +1,46 @@ +""" +The FDv2 polling builders apply the same 30 second minimum poll interval as ``Config``. This +includes an interval that is set directly on a builder. +""" + +import pytest + +from ldclient.async_config import AsyncConfig +from ldclient.config import Config +from ldclient.impl.datasourcev2.async_polling import ( + AsyncFallbackToFDv1PollingDataSourceBuilder, + AsyncPollingDataSourceBuilder +) +from ldclient.impl.datasourcev2.polling import ( + FallbackToFDv1PollingDataSourceBuilder, + PollingDataSourceBuilder +) + +SYNC_BUILDERS = [PollingDataSourceBuilder, FallbackToFDv1PollingDataSourceBuilder] +ASYNC_BUILDERS = [AsyncPollingDataSourceBuilder, AsyncFallbackToFDv1PollingDataSourceBuilder] + + +@pytest.mark.parametrize('builder_class', SYNC_BUILDERS) +@pytest.mark.parametrize('interval, expected', [(1, 30), (30, 30), (45, 45)]) +def test_builder_interval_has_a_minimum(builder_class, interval, expected): + source = builder_class().poll_interval(interval).build(Config('sdk-key')) + assert source._poll_interval == expected + + +@pytest.mark.parametrize('builder_class', SYNC_BUILDERS) +def test_builder_uses_the_config_interval_when_none_is_set(builder_class): + source = builder_class().build(Config('sdk-key', poll_interval=60)) + assert source._poll_interval == 60 + + +@pytest.mark.parametrize('builder_class', ASYNC_BUILDERS) +@pytest.mark.parametrize('interval, expected', [(1, 30), (30, 30), (45, 45)]) +def test_async_builder_interval_has_a_minimum(builder_class, interval, expected): + source = builder_class().poll_interval(interval).build(AsyncConfig('sdk-key')) + assert source._poll_interval == expected + + +@pytest.mark.parametrize('builder_class', ASYNC_BUILDERS) +def test_async_builder_uses_the_config_interval_when_none_is_set(builder_class): + source = builder_class().build(AsyncConfig('sdk-key', poll_interval=60)) + assert source._poll_interval == 60 diff --git a/ldclient/testing/impl/datasourcev2/test_requester_http.py b/ldclient/testing/impl/datasourcev2/test_requester_http.py new file mode 100644 index 00000000..d6562b7e --- /dev/null +++ b/ldclient/testing/impl/datasourcev2/test_requester_http.py @@ -0,0 +1,230 @@ +""" +HTTP behavior of the FDv2 polling requesters and streaming connection: ETag +caching and the request headers they send. +""" + +import inspect +from urllib.parse import parse_qs, urlsplit + +import pytest + +from ldclient.config import Config +from ldclient.impl.datasourcev2 import async_streaming, streaming +from ldclient.impl.datasourcev2.async_polling import ( + AiohttpFDv1PollingRequester, + AiohttpPollingRequester +) +from ldclient.impl.datasourcev2.polling import ( + Urllib3FDv1PollingRequester, + Urllib3PollingRequester +) +from ldclient.impl.http import ASYNC_USER_AGENT, SYNC_USER_AGENT +from ldclient.impl.util import _Success +from ldclient.interfaces import IntentCode, Selector +from ldclient.testing.http_util import ( + BasicResponse, + ChunkedResponse, + JsonResponse, + SequentialHandler, + start_server +) +from ldclient.testing.mock_components import MockSelectorStore +from ldclient.version import VERSION + +FDV2_PAYLOAD = { + 'events': [ + { + 'event': 'server-intent', + 'data': {'payloads': [{'id': 'p1', 'target': 461, 'intentCode': 'xfer-full', 'reason': 'payload-missing'}]}, + }, + { + 'event': 'payload-transferred', + 'data': {'state': '(p:p1:461)', 'id': 'p1', 'version': 461}, + }, + ] +} + +FDV1_PAYLOAD: dict = {'flags': {}, 'segments': {}} + +REQUESTERS = [ + pytest.param(Urllib3PollingRequester, SYNC_USER_AGENT, '/sdk/poll', FDV2_PAYLOAD, id='urllib3-fdv2'), + pytest.param(Urllib3FDv1PollingRequester, SYNC_USER_AGENT, '/sdk/latest-all', FDV1_PAYLOAD, id='urllib3-fdv1'), + pytest.param(AiohttpPollingRequester, ASYNC_USER_AGENT, '/sdk/poll', FDV2_PAYLOAD, id='aiohttp-fdv2'), + pytest.param(AiohttpFDv1PollingRequester, ASYNC_USER_AGENT, '/sdk/latest-all', FDV1_PAYLOAD, id='aiohttp-fdv1'), +] + +# Each case gives config options, an instance id, and the optional headers it +# expects. None means the header must be absent. +HEADER_CASES = [ + pytest.param( + {}, None, + {'X-LaunchDarkly-Wrapper': None, 'X-LaunchDarkly-Tags': None, 'X-LaunchDarkly-Instance-Id': None}, + id='defaults', + ), + pytest.param( + {'wrapper_name': 'Flask', 'wrapper_version': '0.1.0'}, None, + {'X-LaunchDarkly-Wrapper': 'Flask/0.1.0'}, + id='wrapper-with-version', + ), + pytest.param( + {'wrapper_name': 'Flask'}, None, + {'X-LaunchDarkly-Wrapper': 'Flask'}, + id='wrapper-without-version', + ), + pytest.param( + {'application': {'id': 'my-app', 'version': '1.2.3'}}, None, + {'X-LaunchDarkly-Tags': 'application-id/my-app application-version/1.2.3'}, + id='application-tags', + ), + pytest.param( + {}, 'my-instance-id', + {'X-LaunchDarkly-Instance-Id': 'my-instance-id'}, + id='instance-id', + ), +] + + +def make_config(uri, options=None, instance_id=None): + config = Config('sdk-key', base_uri=uri, stream_uri=uri, **(options or {})) + config._instance_id = instance_id + return config + + +async def fetch(requester, selector=None): + # The sync requesters return a result; the async ones return a coroutine. + result = requester.fetch(selector) + if inspect.isawaitable(result): + result = await result + return result + + +async def close(requester): + if hasattr(requester, 'close'): + await requester.close() + else: + requester._http.clear() + + +def assert_headers(headers, user_agent, expected): + assert headers.get('Authorization') == 'sdk-key' + assert headers.get('User-Agent') == user_agent + '/' + VERSION + for name, value in expected.items(): + assert headers.get(name) == value + + +@pytest.mark.asyncio +@pytest.mark.parametrize('requester_cls, user_agent, path, payload', REQUESTERS) +async def test_requester_sends_etag_and_returns_no_changes_on_304(requester_cls, user_agent, path, payload): + with start_server() as server: + server.for_path(path, SequentialHandler( + JsonResponse(payload, {'ETag': 'my-etag'}), + BasicResponse(304), + )) + config = make_config(server.uri) + requester = requester_cls(config, config.base_uri, config.http) + try: + first = await fetch(requester) + second = await fetch(requester) + finally: + await close(requester) + + first_req = server.require_request() + second_req = server.require_request() + + assert first_req.headers.get('If-None-Match') is None + assert second_req.headers.get('If-None-Match') == 'my-etag' + + assert isinstance(first, _Success) + assert first.value[0].intent_code == IntentCode.TRANSFER_FULL + + # A 304 means the data is current, so the requester reports no changes. + assert isinstance(second, _Success) + change_set = second.value[0] + assert change_set.intent_code == IntentCode.TRANSFER_NONE + assert change_set.changes == [] + assert not change_set.selector.is_defined() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('requester_cls, user_agent, path, payload', REQUESTERS) +async def test_requester_omits_if_none_match_when_response_has_no_etag(requester_cls, user_agent, path, payload): + with start_server() as server: + server.for_path(path, JsonResponse(payload)) + config = make_config(server.uri) + requester = requester_cls(config, config.base_uri, config.http) + try: + await fetch(requester) + await fetch(requester) + finally: + await close(requester) + + server.require_request() + second_req = server.require_request() + + assert second_req.headers.get('If-None-Match') is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize('options, instance_id, expected', HEADER_CASES) +@pytest.mark.parametrize('requester_cls, user_agent, path, payload', REQUESTERS) +async def test_requester_sends_sdk_headers(requester_cls, user_agent, path, payload, options, instance_id, expected): + with start_server() as server: + server.for_path(path, JsonResponse(payload)) + config = make_config(server.uri, options, instance_id) + requester = requester_cls(config, config.base_uri, config.http) + try: + await fetch(requester) + finally: + await close(requester) + + req = server.require_request() + + assert req.method == 'GET' + assert urlsplit(req.path).path == path + assert parse_qs(urlsplit(req.path).query) == {} + assert_headers(req.headers, user_agent, expected) + + +@pytest.mark.parametrize('options, instance_id, expected', HEADER_CASES) +def test_streaming_sends_sdk_headers(options, instance_id, expected): + with start_server() as server: + with ChunkedResponse({'Content-Type': 'text/event-stream'}) as stream: + server.for_path('/sdk/stream', stream) + config = make_config(server.uri, options, instance_id) + sse = streaming.create_sse_client( + config.stream_base_uri, config.http, config.initial_reconnect_delay, config, + MockSelectorStore(Selector.no_selector()), + ) + try: + sse.start() + req = server.await_request() + finally: + sse.close() + + assert req.method == 'GET' + assert urlsplit(req.path).path == '/sdk/stream' + assert_headers(req.headers, SYNC_USER_AGENT, expected) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('options, instance_id, expected', HEADER_CASES) +async def test_async_streaming_sends_sdk_headers(options, instance_id, expected): + with start_server() as server: + with ChunkedResponse({'Content-Type': 'text/event-stream'}) as stream: + server.for_path('/sdk/stream', stream) + config = make_config(server.uri, options, instance_id) + sse, session = async_streaming.create_sse_client( + config.stream_base_uri, config.http, config.initial_reconnect_delay, config, + MockSelectorStore(Selector.no_selector()), + ) + try: + await sse.start() + req = server.await_request() + finally: + await sse.close() + if session is not None: + await session.close() + + assert req.method == 'GET' + assert urlsplit(req.path).path == '/sdk/stream' + assert_headers(req.headers, ASYNC_USER_AGENT, expected) diff --git a/ldclient/testing/impl/datasourcev2/test_stream_init_diagnostics.py b/ldclient/testing/impl/datasourcev2/test_stream_init_diagnostics.py new file mode 100644 index 00000000..7a00dc62 --- /dev/null +++ b/ldclient/testing/impl/datasourcev2/test_stream_init_diagnostics.py @@ -0,0 +1,342 @@ +# pylint: disable=missing-docstring, too-few-public-methods +""" +The FDv2 streaming synchronizers record stream inits through their diagnostic +accumulator. These tests drive sync() with mock SSE clients and read the +recorded inits back from a real _DiagnosticAccumulator. +""" + +import json +from typing import Iterable, List + +import pytest +from ld_eventsource.actions import Action, Start +from ld_eventsource.http import HTTPStatusError +from ld_eventsource.sse_client import Event, Fault + +from ldclient.config import Config +from ldclient.impl.datasourcev2 import async_streaming, streaming +from ldclient.impl.datasourcev2.async_streaming import AsyncStreamingDataSource +from ldclient.impl.datasourcev2.streaming import ( + STREAMING_ENDPOINT, + StreamingDataSource +) +from ldclient.impl.datasystem.protocolv2 import EventName +from ldclient.impl.events.diagnostics import _DiagnosticAccumulator +from ldclient.interfaces import ( + DataSourceState, + IntentCode, + Payload, + Selector, + ServerIntent +) +from ldclient.testing.mock_components import MockSelectorStore + + +class ListBasedSseClient: + """A sync SSE client that replays a fixed sequence of actions.""" + + def __init__(self, actions: Iterable[Action]): + self._actions = actions + + @property + def all(self) -> Iterable[Action]: + return self._actions + + @property + def next_retry_delay(self): + return 1 + + def interrupt(self): + pass + + def close(self): + pass + + +class MockAsyncSSEClient: + """An async SSE client that replays a fixed sequence of actions.""" + + def __init__(self, actions: Iterable[Action]): + self._actions = actions + self.closed = False + self.next_retry_delay = 1 + + @property + def all(self): + return self._gen() + + async def _gen(self): + for action in self._actions: + if self.closed: + return + yield action + + async def interrupt(self): + pass + + async def close(self): + self.closed = True + + +def _sync_source(actions: Iterable[Action], accumulator) -> StreamingDataSource: + config = Config("key") + source = StreamingDataSource( + config.stream_base_uri + STREAMING_ENDPOINT, + config.http, + config.initial_reconnect_delay, + config, + ) + source._sse_client_builder = lambda *args, **kwargs: ListBasedSseClient(actions) + source.set_diagnostic_accumulator(accumulator) + return source + + +def _async_source(actions: Iterable[Action], accumulator) -> AsyncStreamingDataSource: + config = Config("key") + source = AsyncStreamingDataSource( + config.stream_base_uri + STREAMING_ENDPOINT, + config.http, + config.initial_reconnect_delay, + config, + ) + source._sse_client_builder = lambda *args, **kwargs: (MockAsyncSSEClient(actions), None) + source.set_diagnostic_accumulator(accumulator) + return source + + +def _run_sync(actions: Iterable[Action], accumulator) -> list: + source = _sync_source(actions, accumulator) + return list(source.sync(MockSelectorStore(Selector.no_selector()))) + + +async def _run_async(actions: Iterable[Action], accumulator) -> list: + source = _async_source(actions, accumulator) + return [u async for u in source.sync(MockSelectorStore(Selector.no_selector()))] + + +def _inits(accumulator) -> List[dict]: + return accumulator.create_event_and_reset(0, 0)['streamInits'] + + +def _intent(code: IntentCode = IntentCode.TRANSFER_FULL) -> Event: + si = ServerIntent(payload=Payload(id="p1", target=1, code=code, reason="test")) + return Event(event=EventName.SERVER_INTENT, data=json.dumps(si.to_dict())) + + +def _transferred(version: int = 1) -> Event: + sel = Selector(state=f"p:test:{version}", version=version) + return Event(event=EventName.PAYLOAD_TRANSFERRED, data=json.dumps(sel.to_dict())) + + +def _full_payload() -> List[Action]: + return [Start(), _intent(), _transferred()] + + +class _FakeClock: + """Holds a monotonic clock and a wall clock the test steps by hand.""" + + def __init__(self): + self.monotonic = 100.0 + self.wall_millis = 5_000_000 + + def install(self, monkeypatch, module): + monkeypatch.setattr(module, "monotonic_seconds", lambda: self.monotonic) + monkeypatch.setattr(module, "current_time_millis", lambda: self.wall_millis) + + +def _clock_stepping_actions(clock: _FakeClock): + # The generator steps both clocks between the intent and the payload end. + # The monotonic clock advances two seconds. The wall clock jumps back an hour. + yield Start() + yield _intent() + clock.monotonic += 2.0 + clock.wall_millis -= 3_600_000 + yield _transferred() + + +# Sync synchronizer + + +def test_sync_records_successful_init_when_first_payload_arrives(): + accumulator = _DiagnosticAccumulator(1) + + updates = _run_sync(_full_payload(), accumulator) + + assert updates[0].state == DataSourceState.VALID + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['failed'] is False + assert inits[0]['durationMillis'] >= 0 + + +def test_sync_records_successful_init_for_transfer_none_intent(): + accumulator = _DiagnosticAccumulator(1) + + _run_sync([Start(), _intent(IntentCode.TRANSFER_NONE)], accumulator) + + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['failed'] is False + + +def test_sync_start_action_alone_records_nothing(): + accumulator = _DiagnosticAccumulator(1) + + _run_sync([Start(), _intent()], accumulator) + + assert _inits(accumulator) == [] + + +def test_sync_records_one_init_across_multiple_payloads(): + accumulator = _DiagnosticAccumulator(1) + + _run_sync(_full_payload() + [_intent(), _transferred(2)], accumulator) + + assert len(_inits(accumulator)) == 1 + + +def test_sync_records_failed_init_on_recoverable_http_error_then_success(): + accumulator = _DiagnosticAccumulator(1) + + _run_sync([Fault(error=HTTPStatusError(503))] + _full_payload(), accumulator) + + inits = _inits(accumulator) + assert [i['failed'] for i in inits] == [True, False] + assert all(i['durationMillis'] >= 0 for i in inits) + + +def test_sync_records_failed_init_on_unrecoverable_http_error(): + accumulator = _DiagnosticAccumulator(1) + + updates = _run_sync([Fault(error=HTTPStatusError(401))] + _full_payload(), accumulator) + + assert updates[-1].state == DataSourceState.OFF + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['failed'] is True + + +def test_sync_records_failed_init_on_network_fault(): + accumulator = _DiagnosticAccumulator(1) + + _run_sync([Fault(error=ConnectionError("connection refused"))] + _full_payload(), accumulator) + + inits = _inits(accumulator) + assert [i['failed'] for i in inits] == [True, False] + + +def test_sync_init_duration_uses_monotonic_clock_across_wall_clock_step(monkeypatch): + clock = _FakeClock() + clock.install(monkeypatch, streaming) + accumulator = _DiagnosticAccumulator(1) + + _run_sync(_clock_stepping_actions(clock), accumulator) + + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['durationMillis'] == 2000 + assert inits[0]['timestamp'] == clock.wall_millis + assert inits[0]['failed'] is False + + +def test_sync_reconnect_after_clean_close_records_no_second_init(): + # A Fault with no error is ignored, so the baseline stays cleared. + # The reconnect's payload records nothing. + accumulator = _DiagnosticAccumulator(1) + + _run_sync(_full_payload() + [Fault(error=None)] + _full_payload(), accumulator) + + assert len(_inits(accumulator)) == 1 + + +# Async synchronizer + + +@pytest.mark.asyncio +async def test_async_records_successful_init_when_first_payload_arrives(): + accumulator = _DiagnosticAccumulator(1) + + updates = await _run_async(_full_payload(), accumulator) + + assert updates[0].state == DataSourceState.VALID + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['failed'] is False + assert inits[0]['durationMillis'] >= 0 + + +@pytest.mark.asyncio +async def test_async_start_action_alone_records_nothing(): + accumulator = _DiagnosticAccumulator(1) + + await _run_async([Start(), _intent()], accumulator) + + assert _inits(accumulator) == [] + + +@pytest.mark.asyncio +async def test_async_records_one_init_across_multiple_payloads(): + accumulator = _DiagnosticAccumulator(1) + + await _run_async(_full_payload() + [_intent(), _transferred(2)], accumulator) + + assert len(_inits(accumulator)) == 1 + + +@pytest.mark.asyncio +async def test_async_records_failed_init_on_recoverable_http_error_then_success(): + accumulator = _DiagnosticAccumulator(1) + + await _run_async([Fault(error=HTTPStatusError(503))] + _full_payload(), accumulator) + + inits = _inits(accumulator) + assert [i['failed'] for i in inits] == [True, False] + assert all(i['durationMillis'] >= 0 for i in inits) + + +@pytest.mark.asyncio +async def test_async_records_failed_init_on_unrecoverable_http_error(): + accumulator = _DiagnosticAccumulator(1) + + updates = await _run_async([Fault(error=HTTPStatusError(401))] + _full_payload(), accumulator) + + assert updates[-1].state == DataSourceState.OFF + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['failed'] is True + + +@pytest.mark.asyncio +async def test_async_records_failed_init_on_network_fault(): + accumulator = _DiagnosticAccumulator(1) + + await _run_async([Fault(error=ConnectionError("connection refused"))] + _full_payload(), accumulator) + + inits = _inits(accumulator) + assert [i['failed'] for i in inits] == [True, False] + + +@pytest.mark.asyncio +async def test_async_init_duration_uses_monotonic_clock_across_wall_clock_step(monkeypatch): + clock = _FakeClock() + clock.install(monkeypatch, async_streaming) + accumulator = _DiagnosticAccumulator(1) + + await _run_async(_clock_stepping_actions(clock), accumulator) + + inits = _inits(accumulator) + assert len(inits) == 1 + assert inits[0]['durationMillis'] == 2000 + assert inits[0]['timestamp'] == clock.wall_millis + assert inits[0]['failed'] is False + + +@pytest.mark.asyncio +async def test_async_reconnect_after_clean_close_records_no_second_init(): + # A Fault with no error is ignored, so the baseline stays cleared. + # The reconnect's payload records nothing. + accumulator = _DiagnosticAccumulator(1) + + await _run_async(_full_payload() + [Fault(error=None)] + _full_payload(), accumulator) + + assert len(_inits(accumulator)) == 1 diff --git a/ldclient/testing/impl/datasystem/test_fdv2_flag_change_propagation.py b/ldclient/testing/impl/datasystem/test_fdv2_flag_change_propagation.py new file mode 100644 index 00000000..2a451be5 --- /dev/null +++ b/ldclient/testing/impl/datasystem/test_fdv2_flag_change_propagation.py @@ -0,0 +1,292 @@ +import inspect +from typing import Iterable, List, Tuple, Union + +import pytest +from mock import patch + +from ldclient.impl.datasystem.async_store import AsyncStore +from ldclient.impl.datasystem.store import Store +from ldclient.impl.listeners import Listeners +from ldclient.impl.model.feature_flag import FeatureFlag +from ldclient.impl.model.segment import Segment +from ldclient.interfaces import ( + ChangeSet, + ChangeSetBuilder, + IntentCode, + ObjectKind, + Selector +) +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 + +Item = Union[FeatureFlag, Segment] + + +def _kind_of(item: Item) -> ObjectKind: + return ObjectKind.FLAG if isinstance(item, FeatureFlag) else ObjectKind.SEGMENT + + +def full_transfer(items: Iterable[Item]) -> ChangeSet: + builder = ChangeSetBuilder() + builder.start(IntentCode.TRANSFER_FULL) + for item in items: + builder.add_put(_kind_of(item), item.key, item.version, item.to_json_dict()) + return builder.finish(Selector.new_selector('full', 1)) + + +def delta(puts: Iterable[Item] = (), deletes: Iterable[Tuple[ObjectKind, str, int]] = ()) -> ChangeSet: + builder = ChangeSetBuilder() + builder.start(IntentCode.TRANSFER_CHANGES) + for item in puts: + builder.add_put(_kind_of(item), item.key, item.version, item.to_json_dict()) + for kind, key, version in deletes: + builder.add_delete(kind, key, version) + return builder.finish(Selector.new_selector('delta', 2)) + + +def segment_match_rule(segment_key: str) -> dict: + return FlagRuleBuilder().variation(0).id('rule_id').clauses(make_clause('user', 'segmentMatch', 'segmentMatch', segment_key)).build() + + +def basic_data() -> List[Item]: + return [ + FlagBuilder('flag1').version(1).on(False).build(), + FlagBuilder('flag2').version(1).on(False).build(), + FlagBuilder('flag3').version(1).rules(segment_match_rule('segment2')).build(), + SegmentBuilder('segment1').version(1).build(), + SegmentBuilder('segment2').version(1).build(), + ] + + +def prereq_data() -> List[Item]: + # flag1 -> flag2 -> (flag3, flag4, flag6); flag6 -> segment2 -> segment1. + return [ + FlagBuilder('flag1').version(1).on(False).prerequisite('flag2', 0).build(), + FlagBuilder('flag2').version(1).on(False).prerequisite('flag3', 0).prerequisite('flag4', 0).prerequisite('flag6', 0).build(), + FlagBuilder('flag3').version(1).on(False).build(), + FlagBuilder('flag4').version(1).on(False).build(), + FlagBuilder('flag5').version(1).on(False).build(), + FlagBuilder('flag6').version(1).rules(segment_match_rule('segment2')).build(), + SegmentBuilder('segment1').version(1).build(), + SegmentBuilder('segment2').version(1).rules(SegmentRuleBuilder().clauses(make_clause('user', 'segmentMatch', 'segmentMatch', 'segment1')).build()).build(), + ] + + +class Harness: + """Wraps a sync or async FDv2 store so tests drive both the same way.""" + + def __init__(self, kind: str): + self.flag_change_listeners = Listeners() + store_class = Store if kind == 'sync' else AsyncStore + self.store = store_class(self.flag_change_listeners, Listeners()) + + async def apply(self, change_set: ChangeSet) -> None: + result = self.store.apply(change_set, False) + if inspect.isawaitable(result): + await result + + def listen(self) -> SpyListener: + spy = SpyListener() + self.flag_change_listeners.add(spy) + return spy + + +@pytest.fixture(params=['sync', 'async']) +def harness(request) -> Harness: + return Harness(request.param) + + +def changed_keys(spy: SpyListener) -> List[str]: + # Events arrive in no guaranteed order, so sort them. + return sorted(change.key for change in spy.statuses) + + +@pytest.mark.asyncio +async def test_first_full_transfer_notifies_for_every_flag(harness): + spy = harness.listen() + + await harness.apply(full_transfer(basic_data())) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag3'] + + +@pytest.mark.asyncio +async def test_full_transfer_notifies_only_for_changed_added_and_removed_flags(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + # flag1 changes version, flag4 is new, and flag2 and flag3 are gone. + await harness.apply(full_transfer([ + FlagBuilder('flag1').version(2).on(False).build(), + FlagBuilder('flag4').version(1).on(False).build(), + ])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag3', 'flag4'] + + +@pytest.mark.asyncio +async def test_full_transfer_with_identical_data_does_not_notify(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(full_transfer(prereq_data())) + + assert spy.statuses == [] + + +@pytest.mark.asyncio +async def test_full_transfer_notifies_flags_that_depend_on_a_changed_segment(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + data = [item for item in prereq_data() if item.key != 'segment1'] + data.append(SegmentBuilder('segment1').version(2).build()) + await harness.apply(full_transfer(data)) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag6'] + + +@pytest.mark.asyncio +async def test_put_flag_notifies_for_that_flag(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[FlagBuilder('flag1').version(2).on(False).build()])) + + assert changed_keys(spy) == ['flag1'] + + +@pytest.mark.asyncio +async def test_put_segment_notifies_flags_that_reference_it(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[SegmentBuilder('segment2').version(2).build()])) + + assert changed_keys(spy) == ['flag3'] + + +@pytest.mark.asyncio +async def test_put_unreferenced_segment_does_not_notify(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[SegmentBuilder('segment1').version(2).build()])) + + assert spy.statuses == [] + + +@pytest.mark.asyncio +async def test_put_prerequisite_notifies_dependent_flags_transitively(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[FlagBuilder('flag4').version(2).on(False).build()])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag4'] + + +@pytest.mark.asyncio +async def test_adding_a_prerequisite_notifies_the_flag_and_its_dependents(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[FlagBuilder('flag3').version(2).on(False).prerequisite('flag4', 0).build()])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag3'] + + +@pytest.mark.asyncio +async def test_removing_a_prerequisite_notifies_the_flag_and_its_dependents(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[FlagBuilder('flag2').version(2).on(False).prerequisite('flag3', 0).build()])) + + assert changed_keys(spy) == ['flag1', 'flag2'] + + +@pytest.mark.asyncio +async def test_removed_prerequisite_no_longer_propagates_changes(harness): + await harness.apply(full_transfer(prereq_data())) + await harness.apply(delta(puts=[FlagBuilder('flag2').version(2).on(False).prerequisite('flag3', 0).build()])) + spy = harness.listen() + + await harness.apply(delta(puts=[FlagBuilder('flag4').version(2).on(False).build()])) + + assert changed_keys(spy) == ['flag4'] + + +@pytest.mark.asyncio +async def test_delete_flag_notifies_for_that_flag(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + await harness.apply(delta(deletes=[(ObjectKind.FLAG, 'flag1', 2)])) + + assert changed_keys(spy) == ['flag1'] + + +@pytest.mark.asyncio +async def test_delete_prerequisite_notifies_dependent_flags_transitively(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(deletes=[(ObjectKind.FLAG, 'flag4', 2)])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag4'] + + +@pytest.mark.asyncio +async def test_put_segment_notifies_through_segment_rules_and_prerequisites(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(puts=[SegmentBuilder('segment1').version(2).build()])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag6'] + + +@pytest.mark.asyncio +async def test_delete_segment_notifies_dependent_flags_transitively(harness): + await harness.apply(full_transfer(prereq_data())) + spy = harness.listen() + + await harness.apply(delta(deletes=[(ObjectKind.SEGMENT, 'segment2', 2)])) + + assert changed_keys(spy) == ['flag1', 'flag2', 'flag6'] + + +@pytest.mark.asyncio +async def test_transfer_none_does_not_notify(harness): + await harness.apply(full_transfer(basic_data())) + spy = harness.listen() + + await harness.apply(ChangeSetBuilder.no_changes()) + + assert spy.statuses == [] + + +@pytest.mark.asyncio +async def test_no_listener_skips_change_computation(harness): + store = harness.store + with patch.object(store._dependency_tracker, 'add_affected_items') as add_affected, \ + patch.object(store, '_compute_changed_items_for_full_data_set') as compute_full, \ + patch.object(store._memory_store, 'all', wraps=store._memory_store.all) as read_all: + await harness.apply(full_transfer(prereq_data())) + await harness.apply(full_transfer(basic_data())) + await harness.apply(delta(puts=[FlagBuilder('flag1').version(2).build()])) + + add_affected.assert_not_called() + compute_full.assert_not_called() + read_all.assert_not_called() + + # The store still applies the data. + assert store.get_active_store().get(FEATURES, 'flag1').version == 2 diff --git a/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py b/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py new file mode 100644 index 00000000..b470e0dc --- /dev/null +++ b/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py @@ -0,0 +1,220 @@ +import time +from typing import Tuple + +from mock import Mock + +from ldclient.impl.datasystem import fdv2_common +from ldclient.impl.datasystem.fdv2_common import ( + DataSourceStatusProviderImpl, + DataStoreStatusProviderImpl +) +from ldclient.impl.listeners import Listeners +from ldclient.interfaces import ( + DataSourceErrorInfo, + DataSourceErrorKind, + DataSourceState, + DataStoreStatus +) +from ldclient.testing.test_util import SpyListener + + +def make_error(message: str = 'boom') -> DataSourceErrorInfo: + return DataSourceErrorInfo(DataSourceErrorKind.NETWORK_ERROR, 0, time.time(), message) + + +def make_source_provider() -> Tuple[DataSourceStatusProviderImpl, SpyListener]: + spy = SpyListener() + provider = DataSourceStatusProviderImpl(Listeners()) + provider.add_listener(spy) + return provider, spy + + +def make_store_provider(store=None) -> Tuple[DataStoreStatusProviderImpl, SpyListener]: + spy = SpyListener() + provider = DataStoreStatusProviderImpl(store, Listeners()) + provider.add_listener(spy) + return provider, spy + + +def test_data_source_status_defaults_to_initializing_without_error(): + provider, _ = make_source_provider() + + assert provider.status.state == DataSourceState.INITIALIZING + assert provider.status.error is None + + +def test_interrupted_while_initializing_stays_initializing(): + provider, spy = make_source_provider() + + provider.update_status(DataSourceState.INTERRUPTED, None) + + assert provider.status.state == DataSourceState.INITIALIZING + assert provider.status.error is None + assert spy.statuses == [] + + +def test_interrupted_with_error_while_initializing_reports_initializing_with_error(): + provider, spy = make_source_provider() + error = make_error() + + provider.update_status(DataSourceState.INTERRUPTED, error) + + assert provider.status.state == DataSourceState.INITIALIZING + assert provider.status.error is error + assert len(spy.statuses) == 1 + + +def test_state_change_notifies_listener_once(): + provider, spy = make_source_provider() + + provider.update_status(DataSourceState.VALID, None) + + assert len(spy.statuses) == 1 + assert spy.statuses[0].state == DataSourceState.VALID + + +def test_same_state_without_error_does_not_notify_again(): + provider, spy = make_source_provider() + + provider.update_status(DataSourceState.VALID, None) + provider.update_status(DataSourceState.VALID, None) + assert len(spy.statuses) == 1 + + provider.update_status(DataSourceState.INTERRUPTED, None) + provider.update_status(DataSourceState.INTERRUPTED, None) + assert len(spy.statuses) == 2 + + +def test_same_state_with_new_error_notifies_and_keeps_since(): + provider, spy = make_source_provider() + provider.update_status(DataSourceState.VALID, None) + since = provider.status.since + error = make_error() + + provider.update_status(DataSourceState.VALID, error) + + assert len(spy.statuses) == 2 + assert spy.statuses[1].error is error + assert provider.status.since == since + + +def test_state_change_updates_since(monkeypatch): + provider, _ = make_source_provider() + monkeypatch.setattr(fdv2_common.time, 'time', lambda: 1000.0) + provider.update_status(DataSourceState.VALID, None) + assert provider.status.since == 1000.0 + + monkeypatch.setattr(fdv2_common.time, 'time', lambda: 2000.0) + provider.update_status(DataSourceState.INTERRUPTED, None) + + assert provider.status.since == 2000.0 + + +def test_error_is_kept_when_later_update_has_no_error(): + provider, _ = make_source_provider() + error = make_error() + provider.update_status(DataSourceState.VALID, None) + provider.update_status(DataSourceState.INTERRUPTED, error) + + provider.update_status(DataSourceState.VALID, None) + + assert provider.status.state == DataSourceState.VALID + assert provider.status.error is error + + +def test_all_listeners_are_notified_for_a_single_change(): + provider, spy1 = make_source_provider() + spy2 = SpyListener() + provider.add_listener(spy2) + + provider.update_status(DataSourceState.VALID, None) + + assert len(spy1.statuses) == 1 + assert len(spy2.statuses) == 1 + + +def test_removed_data_source_listener_is_not_notified(): + provider, spy = make_source_provider() + provider.update_status(DataSourceState.VALID, None) + + provider.remove_listener(spy) + provider.update_status(DataSourceState.INTERRUPTED, None) + + assert len(spy.statuses) == 1 + + +def test_valid_after_off_changes_state_to_valid(): + # FDv2 moves to the next synchronizer after one reports OFF, so OFF is not terminal. + provider, spy = make_source_provider() + provider.update_status(DataSourceState.VALID, None) + provider.update_status(DataSourceState.OFF, None) + + provider.update_status(DataSourceState.VALID, None) + + assert provider.status.state == DataSourceState.VALID + assert [s.state for s in spy.statuses] == [DataSourceState.VALID, DataSourceState.OFF, DataSourceState.VALID] + + +def test_data_store_status_defaults_to_available_and_not_stale(): + provider, _ = make_store_provider() + + assert provider.status == DataStoreStatus(True, False) + + +def test_data_store_status_change_notifies_and_updates_status(): + provider, spy = make_store_provider() + unavailable = DataStoreStatus(False, False) + + provider.update_status(unavailable) + + assert provider.status == unavailable + assert spy.statuses == [unavailable] + + +def test_data_store_unchanged_status_does_not_notify(): + provider, spy = make_store_provider() + + provider.update_status(DataStoreStatus(True, False)) + assert spy.statuses == [] + + provider.update_status(DataStoreStatus(False, False)) + provider.update_status(DataStoreStatus(False, False)) + assert len(spy.statuses) == 1 + + +def test_data_store_status_returns_a_copy(): + provider, _ = make_store_provider() + provider.update_status(DataStoreStatus(False, True)) + + first = provider.status + second = provider.status + + assert first == second + assert first is not second + + +def test_removed_data_store_listener_is_not_notified(): + provider, spy = make_store_provider() + provider.update_status(DataStoreStatus(False, False)) + + provider.remove_listener(spy) + provider.update_status(DataStoreStatus(True, True)) + + assert len(spy.statuses) == 1 + + +def test_monitoring_is_disabled_without_a_store(): + provider, _ = make_store_provider(None) + + assert not provider.is_monitoring_enabled() + + +def test_monitoring_delegates_to_the_store(): + store = Mock() + store.is_monitoring_enabled.return_value = True + provider, _ = make_store_provider(store) + + assert provider.is_monitoring_enabled() + + store.is_monitoring_enabled.return_value = False + assert not provider.is_monitoring_enabled() From cd55404e0ccee6263231143886e989cb26c38450 Mon Sep 17 00:00:00 2001 From: Matthew Keeler Date: Thu, 5 Nov 2026 13:35:30 -0500 Subject: [PATCH 2/2] fix: Report OFF only when the FDv2 data system stops A synchronizer that reports OFF has failed, but the data system goes on with the next synchronizer. The data system now reports that as INTERRUPTED, so status listeners no longer see OFF followed by VALID. The data system reports OFF when it stops, which it did not do before, and OFF is now the last status that listeners receive. --- ldclient/impl/datasystem/async_fdv2.py | 8 +- ldclient/impl/datasystem/fdv2.py | 8 +- ldclient/impl/datasystem/fdv2_common.py | 5 + .../datasystem/test_fdv2_status_lifecycle.py | 141 ++++++++++++++++++ .../datasystem/test_fdv2_status_providers.py | 12 +- 5 files changed, 165 insertions(+), 9 deletions(-) create mode 100644 ldclient/testing/impl/datasystem/test_fdv2_status_lifecycle.py diff --git a/ldclient/impl/datasystem/async_fdv2.py b/ldclient/impl/datasystem/async_fdv2.py index dc30d03a..80d06ec7 100644 --- a/ldclient/impl/datasystem/async_fdv2.py +++ b/ldclient/impl/datasystem/async_fdv2.py @@ -324,6 +324,8 @@ async def stop(self): # Wait for the coordinator's background work to complete await self._runner.stop_all(timeout=5.0) + self._data_source_status_provider.update_status(DataSourceState.OFF, None) + # Close the store await self._store.close() @@ -591,8 +593,10 @@ async def reader(): if update.state == DataSourceState.VALID and not set_on_ready.is_set(): set_on_ready.set() - # Update status - self._data_source_status_provider.update_status(update.state, update.error) + # A synchronizer that reports OFF has failed, but the data system goes on with the + # next synchronizer. The data system reports OFF only when it stops. + status_state = DataSourceState.INTERRUPTED if update.state == DataSourceState.OFF else update.state + self._data_source_status_provider.update_status(status_state, update.error) # Check if we should fall back to FDv1 immediately. fallback_to_fdv1 # may ride along on a Valid update (payload + directive in the same diff --git a/ldclient/impl/datasystem/fdv2.py b/ldclient/impl/datasystem/fdv2.py index 685beac9..0b128c44 100644 --- a/ldclient/impl/datasystem/fdv2.py +++ b/ldclient/impl/datasystem/fdv2.py @@ -292,6 +292,8 @@ def stop(self): if thread.is_alive(): log.warning("Thread %s did not terminate in time", thread.name) + self._data_source_status_provider.update_status(DataSourceState.OFF, None) + # Close the store self._store.close() @@ -569,8 +571,10 @@ def reader(self: 'FDv2'): if update.state == DataSourceState.VALID and not set_on_ready.is_set(): set_on_ready.set() - # Update status - self._data_source_status_provider.update_status(update.state, update.error) + # A synchronizer that reports OFF has failed, but the data system goes on with the + # next synchronizer. The data system reports OFF only when it stops. + status_state = DataSourceState.INTERRUPTED if update.state == DataSourceState.OFF else update.state + self._data_source_status_provider.update_status(status_state, update.error) # Check if we should fall back to FDv1 immediately. fallback_to_fdv1 # may ride along on a Valid update (payload + directive in the same diff --git a/ldclient/impl/datasystem/fdv2_common.py b/ldclient/impl/datasystem/fdv2_common.py index cc50814d..e6dbba27 100644 --- a/ldclient/impl/datasystem/fdv2_common.py +++ b/ldclient/impl/datasystem/fdv2_common.py @@ -44,6 +44,11 @@ def update_status(self, new_state: DataSourceState, new_error: Optional[DataSour with self.__lock.write(): old_status = self.__status + # OFF is terminal. Work that is still in progress when the data system stops must not + # report a status after OFF. + if old_status.state == DataSourceState.OFF: + return + if new_state == DataSourceState.INTERRUPTED and old_status.state == DataSourceState.INITIALIZING: new_state = DataSourceState.INITIALIZING diff --git a/ldclient/testing/impl/datasystem/test_fdv2_status_lifecycle.py b/ldclient/testing/impl/datasystem/test_fdv2_status_lifecycle.py new file mode 100644 index 00000000..27b82039 --- /dev/null +++ b/ldclient/testing/impl/datasystem/test_fdv2_status_lifecycle.py @@ -0,0 +1,141 @@ +""" +The FDv2 data system reports OFF only as its last status. A synchronizer that reports OFF has +failed, but the data system goes on with the next synchronizer, so it reports INTERRUPTED. The +data system reports OFF when it stops, or when it has no synchronizer left. +""" + +import asyncio +from threading import Event +from typing import AsyncGenerator, List + +import pytest +from mock import Mock + +from ldclient.async_config import AsyncConfig, AsyncDataSystemConfig +from ldclient.config import Config, DataSourceBuilder, DataSystemConfig +from ldclient.impl.datasystem.async_fdv2 import AsyncFDv2 +from ldclient.impl.datasystem.fdv2 import FDv2 +from ldclient.integrations.test_datav2 import TestDataV2 +from ldclient.interfaces import ( + DataSourceErrorInfo, + DataSourceErrorKind, + DataSourceState, + DataSourceStatus, + SelectorStore, + Update +) + +ERROR = DataSourceErrorInfo(DataSourceErrorKind.ERROR_RESPONSE, 401, 0, 'unauthorized') + + +class _Builder(DataSourceBuilder): + def __init__(self, source): + self._source = source + + def build(self, config): + return self._source + + +class _ListAsyncSynchronizer: + """An async synchronizer that yields a fixed list of updates and then completes.""" + + def __init__(self, updates: List[Update]): + self._updates = updates + + @property + def name(self) -> str: + return 'list-synchronizer' + + async def sync(self, ss: SelectorStore) -> AsyncGenerator[Update, None]: + for update in self._updates: + yield update + + async def stop(self) -> None: + pass + + +class _StateRecorder: + def __init__(self): + self.states: List[DataSourceState] = [] + self.valid_after_interrupted = Event() + + def __call__(self, status: DataSourceStatus): + self.states.append(status.state) + if status.state == DataSourceState.VALID and DataSourceState.INTERRUPTED in self.states: + self.valid_after_interrupted.set() + + +def _failing_synchronizer() -> Mock: + synchronizer = Mock() + synchronizer.name = 'failing-synchronizer' + synchronizer.sync.return_value = iter([Update(state=DataSourceState.VALID), Update(state=DataSourceState.OFF, error=ERROR)]) + return synchronizer + + +def _test_data() -> TestDataV2: + td = TestDataV2.data_source() + td.update(td.flag('flag').on(True)) + return td + + +def test_synchronizer_off_is_reported_as_interrupted_before_the_next_synchronizer(): + td = _test_data() + fdv2 = FDv2(Config('sdk-key'), DataSystemConfig(initializers=None, synchronizers=[_Builder(_failing_synchronizer()), td.builder])) + recorder = _StateRecorder() + fdv2.data_source_status_provider.add_listener(recorder) + + fdv2.start(Event()) + try: + assert recorder.valid_after_interrupted.wait(2) + assert DataSourceState.OFF not in recorder.states + assert fdv2.data_source_status_provider.status.error == ERROR + finally: + fdv2.stop() + + +def test_stop_reports_off(): + td = _test_data() + fdv2 = FDv2(Config('sdk-key'), DataSystemConfig(initializers=None, synchronizers=[td.builder])) + ready = Event() + fdv2.start(ready) + assert ready.wait(2) + assert fdv2.data_source_status_provider.status.state == DataSourceState.VALID + + fdv2.stop() + + assert fdv2.data_source_status_provider.status.state == DataSourceState.OFF + + +@pytest.mark.asyncio +async def test_async_synchronizer_off_is_reported_as_interrupted_before_the_next_synchronizer(): + td = _test_data() + failing = _ListAsyncSynchronizer([Update(state=DataSourceState.VALID), Update(state=DataSourceState.OFF, error=ERROR)]) + fdv2 = AsyncFDv2(AsyncConfig('sdk-key'), AsyncDataSystemConfig(synchronizers=[_Builder(failing), td.async_builder])) + recorder = _StateRecorder() + fdv2.data_source_status_provider.add_listener(recorder) + + fdv2.start(asyncio.Event()) + try: + for _ in range(200): + if recorder.valid_after_interrupted.is_set(): + break + await asyncio.sleep(0.01) + assert recorder.valid_after_interrupted.is_set() + assert DataSourceState.OFF not in recorder.states + assert fdv2.data_source_status_provider.status.error == ERROR + finally: + await fdv2.stop() + + +@pytest.mark.asyncio +async def test_async_stop_reports_off(): + td = _test_data() + fdv2 = AsyncFDv2(AsyncConfig('sdk-key'), AsyncDataSystemConfig(synchronizers=[td.async_builder])) + ready = asyncio.Event() + fdv2.start(ready) + await asyncio.wait_for(ready.wait(), timeout=2) + assert fdv2.data_source_status_provider.status.state == DataSourceState.VALID + + await fdv2.stop() + + assert fdv2.data_source_status_provider.status.state == DataSourceState.OFF diff --git a/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py b/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py index b470e0dc..1534c44a 100644 --- a/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py +++ b/ldclient/testing/impl/datasystem/test_fdv2_status_providers.py @@ -1,6 +1,7 @@ import time from typing import Tuple +import pytest from mock import Mock from ldclient.impl.datasystem import fdv2_common @@ -143,16 +144,17 @@ def test_removed_data_source_listener_is_not_notified(): assert len(spy.statuses) == 1 -def test_valid_after_off_changes_state_to_valid(): - # FDv2 moves to the next synchronizer after one reports OFF, so OFF is not terminal. +@pytest.mark.parametrize('later_state', [DataSourceState.VALID, DataSourceState.INTERRUPTED, DataSourceState.INITIALIZING]) +def test_off_is_terminal(later_state): provider, spy = make_source_provider() provider.update_status(DataSourceState.VALID, None) provider.update_status(DataSourceState.OFF, None) - provider.update_status(DataSourceState.VALID, None) + provider.update_status(later_state, make_error()) - assert provider.status.state == DataSourceState.VALID - assert [s.state for s in spy.statuses] == [DataSourceState.VALID, DataSourceState.OFF, DataSourceState.VALID] + assert provider.status.state == DataSourceState.OFF + assert provider.status.error is None + assert [s.state for s in spy.statuses] == [DataSourceState.VALID, DataSourceState.OFF] def test_data_store_status_defaults_to_available_and_not_stale():