|
| 1 | +from typing import TYPE_CHECKING |
| 2 | +import sentry_sdk |
| 3 | + |
| 4 | +from sentry_sdk.integrations import DidNotEnable, Integration |
| 5 | + |
| 6 | +try: |
| 7 | + import ldclient |
| 8 | + from ldclient.hook import Hook |
| 9 | + |
| 10 | + if TYPE_CHECKING: |
| 11 | + from ldclient import LDClient |
| 12 | + from ldclient.hook import EvaluationSeriesContext, Metadata |
| 13 | + from ldclient.evaluation import EvaluationDetail |
| 14 | + |
| 15 | + from sentry_sdk._types import Event, ExcInfo |
| 16 | + from typing import Any, Optional |
| 17 | +except ImportError: |
| 18 | + raise DidNotEnable("LaunchDarkly is not installed") |
| 19 | + |
| 20 | + |
| 21 | +class LaunchDarklyIntegration(Integration): |
| 22 | + identifier = "launchdarkly" |
| 23 | + |
| 24 | + @staticmethod |
| 25 | + def get_ldclient(): |
| 26 | + # type: () -> LDClient |
| 27 | + try: |
| 28 | + client = ldclient.get() |
| 29 | + except Exception as exc: |
| 30 | + sentry_sdk.capture_exception(exc) |
| 31 | + raise DidNotEnable( |
| 32 | + "Failed to find LaunchDarkly client instance. " + str(exc) |
| 33 | + ) |
| 34 | + |
| 35 | + if client and client.is_initialized(): |
| 36 | + return client |
| 37 | + raise DidNotEnable("LaunchDarkly client is not initialized") |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def setup_once(): |
| 41 | + # type: () -> None |
| 42 | + def error_processor(event, _exc_info): |
| 43 | + # type: (Event, ExcInfo) -> Optional[Event] |
| 44 | + scope = sentry_sdk.get_current_scope() |
| 45 | + event["contexts"]["flags"] = {"values": scope.flags.get()} |
| 46 | + return event |
| 47 | + |
| 48 | + scope = sentry_sdk.get_current_scope() |
| 49 | + scope.add_error_processor(error_processor) |
| 50 | + |
| 51 | + # Register the hook with the global launchdarkly client. |
| 52 | + client = LaunchDarklyIntegration.get_ldclient() |
| 53 | + client.add_hook(LaunchDarklyHook()) |
| 54 | + |
| 55 | + |
| 56 | +class LaunchDarklyHook(Hook): |
| 57 | + |
| 58 | + @property |
| 59 | + def metadata(self): |
| 60 | + # type: () -> Metadata |
| 61 | + return Metadata(name="sentry-on-error-hook") |
| 62 | + |
| 63 | + def after_evaluation(self, series_context, data, detail): |
| 64 | + # type: (EvaluationSeriesContext, dict[Any, Any], EvaluationDetail) -> dict[Any, Any] |
| 65 | + if isinstance(detail.value, bool): |
| 66 | + flags = sentry_sdk.get_current_scope().flags |
| 67 | + flags.set(series_context.key, detail.value) |
| 68 | + return data |
| 69 | + |
| 70 | + def before_evaluation(self, _series_context, data): |
| 71 | + # type: (EvaluationSeriesContext, dict[Any, Any]) -> dict[Any, Any] |
| 72 | + return data # No-op. |
0 commit comments