-
Notifications
You must be signed in to change notification settings - Fork 571
feat(flags): Add LaunchDarkly Integration #3679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cmanallen
merged 31 commits into
cmanallen/flags-open-feature-integration
from
aliu/launch-darkly
Oct 30, 2024
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
c25b802
Initial src and dependency code
aliu39 e60e1a4
Move get_ldclient to a top-level helper
aliu39 597004b
Add to requirements-testing
aliu39 75a3442
Split up static version from latest
aliu39 43332d2
Merge branch 'cmanallen/flags-open-feature-integration' of https://gi…
aliu39 a2e3383
Fix import
aliu39 5165ffb
Pass in client to Integration initializer and basic unit test
aliu39 c9daf17
Add threaded, asyncio, and global ldclient tests
aliu39 d7ae9f5
Change metadata, test not enabled cases
aliu39 7740f43
Add versioned tests to workflows
aliu39 0309b82
Rm doc references
aliu39 cec37dc
Fix split-tox-gh-actions GROUPS
aliu39 22d1024
Add doc references
aliu39 d9775b8
Formatting from pr comments. Max line length=100
aliu39 91eb352
Move hook registration to setup_once
aliu39 2f59b47
Merge branch 'cmanallen/flags-open-feature-integration' into aliu/lau…
cmanallen a9d5099
Fix typing and extract error_processor to common module
cmanallen 50d2dae
Raise if the integration was not enabled before setup_once is called
cmanallen 44aebf3
Rename parameter
cmanallen 144e064
Move hook registration to the init method
cmanallen 13434c3
Update tox to use 3.8 or greater
cmanallen 77d4055
Fix name
cmanallen 8a1a20e
Remove duplicate definition
cmanallen 2dab8c3
Remove another dupe and change naming
cmanallen c97e102
Restrict versions
cmanallen ead840f
Remove integration init
cmanallen bb678c2
Rename extras_require for launchdarkly
cmanallen 08289c2
Try resetting the client
cmanallen a3d90bd
Remove launchdarkly from testing requirements
cmanallen 711fe55
Revert "Remove integration init"
cmanallen 5218c7a
Remove client reset
cmanallen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,3 +16,4 @@ pep8-naming | |
| pre-commit # local linting | ||
| httpcore | ||
| openfeature-sdk | ||
| launchdarkly-server-sdk | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -125,6 +125,7 @@ | |
| "tornado", | ||
| ], | ||
| "Miscellaneous": [ | ||
| "launchdarkly", | ||
| "loguru", | ||
| "openfeature", | ||
| "opentelemetry", | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| from typing import TYPE_CHECKING | ||
| import sentry_sdk | ||
|
|
||
| from sentry_sdk.integrations import DidNotEnable, Integration | ||
| from sentry_sdk.flag_utils import flag_error_processor | ||
|
|
||
| try: | ||
| import ldclient | ||
| from ldclient.hook import Hook, Metadata | ||
|
|
||
| if TYPE_CHECKING: | ||
| from ldclient import LDClient | ||
| from ldclient.hook import EvaluationSeriesContext | ||
| from ldclient.evaluation import EvaluationDetail | ||
|
|
||
| from typing import Any | ||
| except ImportError: | ||
| raise DidNotEnable("LaunchDarkly is not installed") | ||
|
|
||
|
|
||
| class LaunchDarklyIntegration(Integration): | ||
| identifier = "launchdarkly" | ||
|
|
||
| def __init__(self, ld_client=None): | ||
| # type: (LDClient | None) -> None | ||
| """ | ||
| :param client: An initialized LDClient instance. If a client is not provided, this | ||
| integration will attempt to use the shared global instance. | ||
| """ | ||
| try: | ||
| client = ld_client or ldclient.get() | ||
| except Exception as exc: | ||
| raise DidNotEnable("Error getting LaunchDarkly client. " + repr(exc)) | ||
|
|
||
| if not client.is_initialized(): | ||
| raise DidNotEnable("LaunchDarkly client is not initialized.") | ||
|
|
||
| # Register the flag collection hook with the LD client. | ||
| client.add_hook(LaunchDarklyHook()) | ||
|
|
||
| @staticmethod | ||
| def setup_once(): | ||
| # type: () -> None | ||
| scope = sentry_sdk.get_current_scope() | ||
| scope.add_error_processor(flag_error_processor) | ||
|
|
||
|
|
||
| class LaunchDarklyHook(Hook): | ||
|
|
||
| @property | ||
| def metadata(self): | ||
| # type: () -> Metadata | ||
| return Metadata(name="sentry-feature-flag-recorder") | ||
|
|
||
| def after_evaluation(self, series_context, data, detail): | ||
| # type: (EvaluationSeriesContext, dict[Any, Any], EvaluationDetail) -> dict[Any, Any] | ||
| if isinstance(detail.value, bool): | ||
| flags = sentry_sdk.get_current_scope().flags | ||
| flags.set(series_context.key, detail.value) | ||
| return data | ||
|
|
||
| def before_evaluation(self, series_context, data): | ||
| # type: (EvaluationSeriesContext, dict[Any, Any]) -> dict[Any, Any] | ||
| return data # No-op. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import pytest | ||
|
|
||
| pytest.importorskip("ldclient") | ||
aliu39 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import asyncio | ||
| import concurrent.futures as cf | ||
|
|
||
| import ldclient | ||
|
|
||
| import sentry_sdk | ||
| import pytest | ||
|
|
||
| from ldclient import LDClient | ||
| from ldclient.config import Config | ||
| from ldclient.context import Context | ||
| from ldclient.integrations.test_data import TestData | ||
|
|
||
| from sentry_sdk.integrations import DidNotEnable | ||
| from sentry_sdk.integrations.launchdarkly import LaunchDarklyIntegration | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "use_global_client", | ||
| (False, True), | ||
| ) | ||
| def test_launchdarkly_integration(sentry_init, use_global_client): | ||
| td = TestData.data_source() | ||
| config = Config("sdk-key", update_processor_class=td) | ||
| if use_global_client: | ||
| ldclient.set_config(config) | ||
| sentry_init(integrations=[LaunchDarklyIntegration()]) | ||
| client = ldclient.get() | ||
| else: | ||
| client = LDClient(config=config) | ||
| sentry_init(integrations=[LaunchDarklyIntegration(ld_client=client)]) | ||
|
|
||
| # Set test values | ||
| td.update(td.flag("hello").variation_for_all(True)) | ||
| td.update(td.flag("world").variation_for_all(True)) | ||
|
|
||
| # Evaluate | ||
| client.variation("hello", Context.create("my-org", "organization"), False) | ||
| client.variation("world", Context.create("user1", "user"), False) | ||
| client.variation("other", Context.create("user2", "user"), False) | ||
|
|
||
| assert sentry_sdk.get_current_scope().flags.get() == [ | ||
| {"flag": "hello", "result": True}, | ||
| {"flag": "world", "result": True}, | ||
| {"flag": "other", "result": False}, | ||
| ] | ||
|
|
||
|
|
||
| def test_launchdarkly_integration_threaded(sentry_init): | ||
| td = TestData.data_source() | ||
| client = LDClient(config=Config("sdk-key", update_processor_class=td)) | ||
| sentry_init(integrations=[LaunchDarklyIntegration(ld_client=client)]) | ||
| context = Context.create("user1") | ||
|
|
||
| def task(flag_key): | ||
| # Creates a new isolation scope for the thread. | ||
| # This means the evaluations in each task are captured separately. | ||
| with sentry_sdk.isolation_scope(): | ||
| client.variation(flag_key, context, False) | ||
| return [f["flag"] for f in sentry_sdk.get_current_scope().flags.get()] | ||
|
|
||
| td.update(td.flag("hello").variation_for_all(True)) | ||
| td.update(td.flag("world").variation_for_all(False)) | ||
| # Capture an eval before we split isolation scopes. | ||
| client.variation("hello", context, False) | ||
|
|
||
| with cf.ThreadPoolExecutor(max_workers=2) as pool: | ||
| results = list(pool.map(task, ["world", "other"])) | ||
|
|
||
| assert results[0] == ["hello", "world"] | ||
| assert results[1] == ["hello", "other"] | ||
|
|
||
|
|
||
| def test_launchdarkly_integration_asyncio(sentry_init): | ||
| """Assert concurrently evaluated flags do not pollute one another.""" | ||
| td = TestData.data_source() | ||
| client = LDClient(config=Config("sdk-key", update_processor_class=td)) | ||
| sentry_init(integrations=[LaunchDarklyIntegration(ld_client=client)]) | ||
| context = Context.create("user1") | ||
|
|
||
| async def task(flag_key): | ||
| with sentry_sdk.isolation_scope(): | ||
| client.variation(flag_key, context, False) | ||
| return [f["flag"] for f in sentry_sdk.get_current_scope().flags.get()] | ||
|
|
||
| async def runner(): | ||
| return asyncio.gather(task("world"), task("other")) | ||
|
|
||
| td.update(td.flag("hello").variation_for_all(True)) | ||
| td.update(td.flag("world").variation_for_all(False)) | ||
| client.variation("hello", context, False) | ||
|
|
||
| results = asyncio.run(runner()).result() | ||
| assert results[0] == ["hello", "world"] | ||
| assert results[1] == ["hello", "other"] | ||
|
|
||
|
|
||
| def test_launchdarkly_integration_did_not_enable(monkeypatch): | ||
| # Client is not passed in and set_config wasn't called. | ||
| # TODO: Bad practice to access internals like this. We can skip this test, or remove this | ||
| # case entirely (force user to pass in a client instance). | ||
| ldclient._reset_client() | ||
| try: | ||
| ldclient.__lock.lock() | ||
| ldclient.__config = None | ||
| finally: | ||
| ldclient.__lock.unlock() | ||
|
|
||
| with pytest.raises(DidNotEnable): | ||
| LaunchDarklyIntegration() | ||
|
|
||
| # Client not initialized. | ||
| client = LDClient(config=Config("sdk-key")) | ||
| monkeypatch.setattr(client, "is_initialized", lambda: False) | ||
| with pytest.raises(DidNotEnable): | ||
| LaunchDarklyIntegration(ld_client=client) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.