Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions ldclient/impl/datasystem/async_fdv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,16 @@ def __init__(self, store: AsyncFeatureStore, status_sink: Callable[[DataStoreSta
self._status_sink = status_sink
self._monitoring_enabled = self.is_monitoring_enabled()

# Held for each write and by close(). A write that starts after
# close() does nothing, and close() waits for a write in progress.
self._write_lock = AsyncLock()

self._last_available = True
self._poller: Optional[AsyncRepeatingTask] = None
self._closed = False

async def init(self, all_data: Mapping[VersionedDataKind, Mapping[str, dict]]) -> None:
await self._wrap(lambda: self._store.init(_FeatureStoreDataSetSorter.sort_all_collections(all_data)))
await self._write(lambda: self._store.init(_FeatureStoreDataSetSorter.sort_all_collections(all_data)), None)

async def get(self, kind: VersionedDataKind, key: str) -> Optional[Any]:
return await self._wrap(lambda: self._store.get(kind, key))
Expand All @@ -96,10 +100,10 @@ async def all(self, kind: VersionedDataKind) -> Dict[str, Any]:
return await self._wrap(lambda: self._store.all(kind))

async def upsert(self, kind: VersionedDataKind, item: dict) -> bool:
return await self._wrap(lambda: self._store.upsert(kind, item))
return await self._write(lambda: self._store.upsert(kind, item), False)

async def delete(self, kind: VersionedDataKind, key: str, version: int) -> bool:
return await self._wrap(lambda: self._store.delete(kind, key, version))
return await self._write(lambda: self._store.delete(kind, key, version), False)

@property
def initialized(self) -> bool:
Expand Down Expand Up @@ -135,6 +139,18 @@ async def _wrap(self, fn: Callable):
self._update_availability(False)
raise

async def _write(self, fn: Callable, result_if_closed: Any):
# The failure is reported after the lock is released, as in the sync wrapper.
try:
async with self._write_lock:
if self._closed:
return result_if_closed
return await fn()
except BaseException:
if self._monitoring_enabled:
self._update_availability(False)
raise

def _update_availability(self, available: bool) -> None:
if self._closed:
return
Expand Down Expand Up @@ -173,11 +189,13 @@ async def _check_availability(self) -> None:
async def close(self) -> None:
"""Stops the availability poller and closes the inner store.

Does nothing on a later call, so closing more than once is safe.
Waits for a write in progress. Later writes do nothing. Does nothing on
a later call, so closing more than once is safe.
"""
if self._closed:
return
self._closed = True
async with self._write_lock:
if self._closed:
return
self._closed = True

poller_to_stop = self._poller
self._poller = None
Expand Down
53 changes: 53 additions & 0 deletions ldclient/testing/impl/datasystem/test_async_fdv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,3 +770,56 @@ async def test_successful_ops_pass_through():
assert got is not None and got["key"] == "flag-a"
allf = await wrapper.all(FEATURES)
assert "flag-a" in allf


@pytest.mark.asyncio
async def test_writes_after_close_do_not_reach_the_store():
store = FakeAsyncStore()
statuses: List[DataStoreStatus] = []
wrapper = _AsyncFeatureStoreClientWrapper(store, lambda s: statuses.append(s))
await wrapper.close()

await wrapper.init({FEATURES: {"flag-a": {"key": "flag-a", "version": 1}}})
assert await wrapper.upsert(FEATURES, {"key": "flag-b", "version": 1}) is False
assert await wrapper.delete(FEATURES, "flag-c", 2) is False

assert store.init_calls == []
assert store._data == {FEATURES: {}, SEGMENTS: {}}
assert store.closed is True
assert statuses == []


class SlowUpsertStore(FakeAsyncStore):
"""A store whose upsert waits until the test releases it."""

def __init__(self):
super().__init__()
self.entered = asyncio.Event()
self.release = asyncio.Event()
self.calls: List[str] = []

async def upsert(self, kind: VersionedDataKind, item: dict) -> bool:
self.entered.set()
await self.release.wait()
self.calls.append("upsert")
return True

async def close(self) -> None:
self.calls.append("close")


@pytest.mark.asyncio
async def test_close_waits_for_a_write_in_progress():
store = SlowUpsertStore()
wrapper = _AsyncFeatureStoreClientWrapper(store, lambda _s: None)

writer = asyncio.create_task(wrapper.upsert(FEATURES, {"key": "flag-a", "version": 1}))
await asyncio.wait_for(store.entered.wait(), timeout=2)

closer = asyncio.create_task(wrapper.close())
await asyncio.sleep(0.2)
assert not closer.done()

store.release.set()
await asyncio.wait_for(asyncio.gather(writer, closer), timeout=2)
assert store.calls == ["upsert", "close"]
Loading