|
| 1 | +from typing import TYPE_CHECKING |
| 2 | +import sentry_sdk |
| 3 | + |
| 4 | +from sentry_sdk.integrations import DidNotEnable, Integration |
| 5 | +from sentry_sdk.flag_utils import flag_error_processor |
| 6 | + |
| 7 | +try: |
| 8 | + import ldclient |
| 9 | + from ldclient.hook import Hook, Metadata |
| 10 | + |
| 11 | + if TYPE_CHECKING: |
| 12 | + from ldclient import LDClient |
| 13 | + from ldclient.hook import EvaluationSeriesContext |
| 14 | + from ldclient.evaluation import EvaluationDetail |
| 15 | + |
| 16 | + from typing import Any |
| 17 | +except ImportError: |
| 18 | + raise DidNotEnable("LaunchDarkly is not installed") |
| 19 | + |
| 20 | + |
| 21 | +class LaunchDarklyIntegration(Integration): |
| 22 | + identifier = "launchdarkly" |
| 23 | + |
| 24 | + def __init__(self, ld_client=None): |
| 25 | + # type: (LDClient | None) -> None |
| 26 | + """ |
| 27 | + :param client: An initialized LDClient instance. If a client is not provided, this |
| 28 | + integration will attempt to use the shared global instance. |
| 29 | + """ |
| 30 | + try: |
| 31 | + client = ld_client or ldclient.get() |
| 32 | + except Exception as exc: |
| 33 | + raise DidNotEnable("Error getting LaunchDarkly client. " + repr(exc)) |
| 34 | + |
| 35 | + if not client.is_initialized(): |
| 36 | + raise DidNotEnable("LaunchDarkly client is not initialized.") |
| 37 | + |
| 38 | + # Register the flag collection hook with the LD client. |
| 39 | + client.add_hook(LaunchDarklyHook()) |
| 40 | + |
| 41 | + @staticmethod |
| 42 | + def setup_once(): |
| 43 | + # type: () -> None |
| 44 | + scope = sentry_sdk.get_current_scope() |
| 45 | + scope.add_error_processor(flag_error_processor) |
| 46 | + |
| 47 | + |
| 48 | +class LaunchDarklyHook(Hook): |
| 49 | + |
| 50 | + @property |
| 51 | + def metadata(self): |
| 52 | + # type: () -> Metadata |
| 53 | + return Metadata(name="sentry-feature-flag-recorder") |
| 54 | + |
| 55 | + def after_evaluation(self, series_context, data, detail): |
| 56 | + # type: (EvaluationSeriesContext, dict[Any, Any], EvaluationDetail) -> dict[Any, Any] |
| 57 | + if isinstance(detail.value, bool): |
| 58 | + flags = sentry_sdk.get_current_scope().flags |
| 59 | + flags.set(series_context.key, detail.value) |
| 60 | + return data |
| 61 | + |
| 62 | + def before_evaluation(self, series_context, data): |
| 63 | + # type: (EvaluationSeriesContext, dict[Any, Any]) -> dict[Any, Any] |
| 64 | + return data # No-op. |
0 commit comments