Skip to content
Open
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
2 changes: 1 addition & 1 deletion ldclient/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
8 changes: 6 additions & 2 deletions ldclient/impl/datasource/async_feature_requester.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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:
Expand Down
26 changes: 23 additions & 3 deletions ldclient/impl/datasource/async_polling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, runtime_checkable

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,
Expand All @@ -31,6 +34,12 @@
)


@runtime_checkable
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.

Expand Down Expand Up @@ -69,10 +78,21 @@ 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.
"""
if isinstance(self._requester, _AsyncFeatureRequesterWithHeaders):
return await 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:
Expand Down
8 changes: 8 additions & 0 deletions ldclient/impl/datasource/async_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion ldclient/impl/datasource/async_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions ldclient/impl/datasystem/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]:
Expand Down
4 changes: 4 additions & 0 deletions ldclient/impl/datasystem/async_fdv1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions ldclient/impl/datasystem/async_fdv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
"""
Expand Down
Loading
Loading