dedupe.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import weakref
  2. import sentry_sdk
  3. from sentry_sdk.utils import ContextVar, logger
  4. from sentry_sdk.integrations import Integration
  5. from sentry_sdk.scope import add_global_event_processor
  6. from typing import TYPE_CHECKING
  7. if TYPE_CHECKING:
  8. from typing import Optional
  9. from sentry_sdk._types import Event, Hint
  10. class DedupeIntegration(Integration):
  11. identifier = "dedupe"
  12. def __init__(self) -> None:
  13. self._last_seen = ContextVar("last-seen")
  14. @staticmethod
  15. def setup_once() -> None:
  16. @add_global_event_processor
  17. def processor(event: "Event", hint: "Optional[Hint]") -> "Optional[Event]":
  18. if hint is None:
  19. return event
  20. integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
  21. if integration is None:
  22. return event
  23. exc_info = hint.get("exc_info", None)
  24. if exc_info is None:
  25. return event
  26. last_seen = integration._last_seen.get(None)
  27. if last_seen is not None:
  28. # last_seen is either a weakref or the original instance
  29. last_seen = (
  30. last_seen() if isinstance(last_seen, weakref.ref) else last_seen
  31. )
  32. exc = exc_info[1]
  33. if last_seen is exc:
  34. logger.info("DedupeIntegration dropped duplicated error event %s", exc)
  35. return None
  36. # we can only weakref non builtin types
  37. try:
  38. integration._last_seen.set(weakref.ref(exc))
  39. except TypeError:
  40. integration._last_seen.set(exc)
  41. return event
  42. @staticmethod
  43. def reset_last_seen() -> None:
  44. integration = sentry_sdk.get_client().get_integration(DedupeIntegration)
  45. if integration is None:
  46. return
  47. integration._last_seen.set(None)