|
| 1 | +from functools import wraps |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +import sentry_sdk |
| 5 | +from sentry_sdk.flag_utils import flag_error_processor |
| 6 | +from sentry_sdk.integrations import Integration, DidNotEnable |
| 7 | + |
| 8 | +try: |
| 9 | + from UnleashClient import UnleashClient |
| 10 | +except ImportError: |
| 11 | + raise DidNotEnable("UnleashClient is not installed") |
| 12 | + |
| 13 | + |
| 14 | +class UnleashIntegration(Integration): |
| 15 | + identifier = "unleash" |
| 16 | + |
| 17 | + @staticmethod |
| 18 | + def setup_once(): |
| 19 | + # type: () -> None |
| 20 | + # Wrap and patch evaluation methods (instance methods) |
| 21 | + old_is_enabled = UnleashClient.is_enabled |
| 22 | + old_get_variant = UnleashClient.get_variant |
| 23 | + |
| 24 | + @wraps(old_is_enabled) |
| 25 | + def sentry_is_enabled(self, feature, *args, **kwargs): |
| 26 | + # type: (UnleashClient, str, *Any, **Any) -> Any |
| 27 | + enabled = old_is_enabled(self, feature, *args, **kwargs) |
| 28 | + |
| 29 | + # We have no way of knowing what type of unleash feature this is, so we have to treat |
| 30 | + # it as a boolean / toggle feature. |
| 31 | + flags = sentry_sdk.get_current_scope().flags |
| 32 | + flags.set(feature, enabled) |
| 33 | + |
| 34 | + return enabled |
| 35 | + |
| 36 | + @wraps(old_get_variant) |
| 37 | + def sentry_get_variant(self, feature, *args, **kwargs): |
| 38 | + # type: (UnleashClient, str, *Any, **Any) -> Any |
| 39 | + variant = old_get_variant(self, feature, *args, **kwargs) |
| 40 | + enabled = variant.get("enabled", False) |
| 41 | + |
| 42 | + # Payloads are not always used as the feature's value for application logic. They |
| 43 | + # may be used for metrics or debugging context instead. Therefore, we treat every |
| 44 | + # variant as a boolean toggle, using the `enabled` field. |
| 45 | + flags = sentry_sdk.get_current_scope().flags |
| 46 | + flags.set(feature, enabled) |
| 47 | + |
| 48 | + return variant |
| 49 | + |
| 50 | + UnleashClient.is_enabled = sentry_is_enabled # type: ignore |
| 51 | + UnleashClient.get_variant = sentry_get_variant # type: ignore |
| 52 | + |
| 53 | + # Error processor |
| 54 | + scope = sentry_sdk.get_current_scope() |
| 55 | + scope.add_error_processor(flag_error_processor) |
0 commit comments