Skip to content

Commit 85e948c

Browse files
authored
fix: Prevent an FDv2 initializer result from being applied after close (#583)
1 parent 5721c67 commit 85e948c

4 files changed

Lines changed: 123 additions & 4 deletions

File tree

‎ldclient/impl/datasourcev2/polling.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@ def sync(self, ss: SelectorStore) -> Generator[Update, None, None]:
110110
# The flags are not cleared here. Stop can occur before sync starts, and sync then ends at once.
111111
while self._stop.is_set() is False:
112112
result = self._fetch(ss)
113+
if self._stop.is_set():
114+
# Stop can occur while the request is in progress. The result is not reported.
115+
break
113116
decision = map_polling_result(result)
114117
yield decision.update
115118

@@ -134,7 +137,10 @@ def _fetch(self, ss: SelectorStore) -> PollingResult:
134137
return self._requester.fetch(ss.selector())
135138
except Exception as e: # pylint: disable=broad-except
136139
msg = f"Error: Exception encountered when polling for flags. {e}"
137-
log.warning(msg)
140+
if self._stop.is_set():
141+
log.debug(msg)
142+
else:
143+
log.warning(msg)
138144
return _Fail(error=msg, exception=e)
139145

140146
def _poll(self, ss: SelectorStore) -> BasisResult:
@@ -143,7 +149,11 @@ def _poll(self, ss: SelectorStore) -> BasisResult:
143149
return polling_result_to_basis(result)
144150
except Exception as e: # pylint: disable=broad-except
145151
msg = f"Error: Exception encountered when updating flags. {e}"
146-
log.exception(msg)
152+
if self._stop.is_set():
153+
# The SDK is shutting down, so the error is not reported.
154+
log.debug(msg)
155+
else:
156+
log.exception(msg)
147157

148158
return _Fail(error=msg, exception=e)
149159

‎ldclient/impl/datasystem/fdv2.py‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
DataStoreStatus,
3434
FeatureStore,
3535
FlagChange,
36+
Initializer,
3637
OverrideSource,
3738
ReadOnlyStore,
3839
Synchronizer
@@ -260,6 +261,7 @@ def __init__(
260261
self._stop_event = Event()
261262
self._lock = ReadWriteLock()
262263
self._active_synchronizer: Optional[Synchronizer] = None
264+
self._active_initializer: Optional[Initializer] = None
263265
self._threads: List[Thread] = []
264266
self._environment_id: Optional[str] = None
265267

@@ -361,6 +363,13 @@ def stop(self):
361363
self._stop_event.set()
362364

363365
with self._lock.write():
366+
# An initializer can match the protocol without the stop method.
367+
stop_initializer = getattr(self._active_initializer, "stop", None)
368+
if stop_initializer is not None:
369+
try:
370+
stop_initializer()
371+
except Exception as e:
372+
log.error("Error stopping active initializer: %s", e)
364373
if self._active_synchronizer is not None:
365374
try:
366375
self._active_synchronizer.stop()
@@ -392,6 +401,10 @@ def _run_main_loop(self, set_on_ready: Event):
392401
# Run initializers first
393402
fallback_requested = self._run_initializers(set_on_ready)
394403

404+
# Stop can interrupt an initializer. The synchronizers then do not start.
405+
if self._stop_event.is_set():
406+
return
407+
395408
# If an initializer asked the SDK to fall back to FDv1, halt the
396409
# configured FDv2 chain and switch terminally to the FDv1 Fallback
397410
# Synchronizer (or transition to OFF if none is configured).
@@ -441,7 +454,20 @@ def _run_initializers(self, set_on_ready: Event) -> bool:
441454
initializer = initializer_builder.build(self._config)
442455
log.info("Attempting to initialize via %s", initializer.name)
443456

444-
basis_result = initializer.fetch(self._store)
457+
# Stop sets the stop event before it takes the lock. So stop either sees this
458+
# initializer and stops it, or this check sees the stop event.
459+
with self._lock.write():
460+
if self._stop_event.is_set():
461+
return False
462+
self._active_initializer = initializer
463+
try:
464+
basis_result = initializer.fetch(self._store)
465+
finally:
466+
with self._lock.write():
467+
self._active_initializer = None
468+
469+
if self._stop_event.is_set():
470+
return False
445471

446472
if isinstance(basis_result, _Fail):
447473
log.warning("Initializer %s failed: %s", initializer.name, basis_result.error)

‎ldclient/interfaces.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2073,6 +2073,12 @@ def fetch(self, ss: SelectorStore) -> BasisResult:
20732073
"""
20742074
raise NotImplementedError
20752075

2076+
def stop(self) -> None:
2077+
"""
2078+
stop is called from another thread when the SDK shuts down while fetch is in progress.
2079+
It should make fetch return as soon as possible. The default implementation does nothing.
2080+
"""
2081+
20762082

20772083
@dataclass(frozen=True)
20782084
class Update:

‎ldclient/testing/impl/datasystem/test_fdv2_datasystem.py‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import os
55
import tempfile
6-
from threading import Event
6+
from threading import Event, Timer
77
from typing import List
88

99
import pytest
@@ -880,3 +880,80 @@ def test_does_not_warn_when_payload_filter_key_is_not_configured(caplog):
880880
FDv2(Config(sdk_key="dummy"), DataSystemConfig(initializers=None, synchronizers=None))
881881

882882
assert not any("Payload filtering" in record.message for record in caplog.records)
883+
884+
885+
class _BlockingInitializer(Initializer):
886+
"""An initializer whose fetch waits until stop is called, then returns data."""
887+
888+
def __init__(self):
889+
self.fetching = Event()
890+
self.stopped = Event()
891+
892+
@property
893+
def name(self) -> str:
894+
return "blocking"
895+
896+
def fetch(self, ss: SelectorStore) -> BasisResult:
897+
self.fetching.set()
898+
self.stopped.wait(5)
899+
builder = ChangeSetBuilder()
900+
builder.start(IntentCode.TRANSFER_FULL)
901+
change_set = builder.finish(Selector(state="blocking-state", version=1))
902+
return _Success(value=Basis(change_set=change_set, persist=False, environment_id=None))
903+
904+
def stop(self):
905+
self.stopped.set()
906+
907+
908+
def test_stop_stops_the_initializer_in_progress_and_ignores_its_result():
909+
initializer = _BlockingInitializer()
910+
td = TestDataV2.data_source()
911+
fdv2 = FDv2(
912+
Config(sdk_key="dummy"),
913+
DataSystemConfig(initializers=[_InitializerBuilder(initializer)], synchronizers=[td.builder]),
914+
)
915+
set_on_ready = Event()
916+
fdv2.start(set_on_ready)
917+
assert initializer.fetching.wait(5), "The initializer did not start"
918+
919+
fdv2.stop()
920+
921+
assert initializer.stopped.is_set()
922+
# The initializer returned data after stop. The data system does not apply it.
923+
assert not set_on_ready.is_set()
924+
assert not fdv2.store.initialized
925+
926+
927+
class _InitializerWithoutStop:
928+
"""An initializer that matches the protocol but does not inherit from it, so it has no stop."""
929+
930+
def __init__(self):
931+
self.fetching = Event()
932+
self.release = Event()
933+
934+
@property
935+
def name(self) -> str:
936+
return "without-stop"
937+
938+
def fetch(self, ss: SelectorStore) -> BasisResult:
939+
self.fetching.set()
940+
self.release.wait(5)
941+
return _Fail(error="released")
942+
943+
944+
def test_stop_accepts_an_initializer_in_progress_without_a_stop_method(caplog):
945+
initializer = _InitializerWithoutStop()
946+
fdv2 = FDv2(
947+
Config(sdk_key="dummy"),
948+
DataSystemConfig(initializers=[_InitializerBuilder(initializer)], synchronizers=None),
949+
)
950+
fdv2.start(Event())
951+
assert initializer.fetching.wait(5), "The initializer did not start"
952+
953+
# The initializer cannot be stopped, so release it shortly after stop begins.
954+
release = Timer(0.2, initializer.release.set)
955+
release.start()
956+
fdv2.stop()
957+
release.join()
958+
959+
assert not any(record.levelno >= logging.ERROR for record in caplog.records)

0 commit comments

Comments
 (0)