huey.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import sys
  2. from datetime import datetime
  3. import sentry_sdk
  4. from sentry_sdk.api import continue_trace, get_baggage, get_traceparent
  5. from sentry_sdk.consts import OP, SPANSTATUS
  6. from sentry_sdk.integrations import DidNotEnable, Integration
  7. from sentry_sdk.scope import should_send_default_pii
  8. from sentry_sdk.tracing import (
  9. BAGGAGE_HEADER_NAME,
  10. SENTRY_TRACE_HEADER_NAME,
  11. TransactionSource,
  12. )
  13. from sentry_sdk.utils import (
  14. capture_internal_exceptions,
  15. ensure_integration_enabled,
  16. event_from_exception,
  17. SENSITIVE_DATA_SUBSTITUTE,
  18. reraise,
  19. )
  20. from typing import TYPE_CHECKING
  21. if TYPE_CHECKING:
  22. from typing import Any, Callable, Optional, Union, TypeVar
  23. from sentry_sdk._types import EventProcessor, Event, Hint
  24. from sentry_sdk.utils import ExcInfo
  25. F = TypeVar("F", bound=Callable[..., Any])
  26. try:
  27. from huey.api import Huey, Result, ResultGroup, Task, PeriodicTask
  28. from huey.exceptions import CancelExecution, RetryTask, TaskLockedException
  29. except ImportError:
  30. raise DidNotEnable("Huey is not installed")
  31. HUEY_CONTROL_FLOW_EXCEPTIONS = (CancelExecution, RetryTask, TaskLockedException)
  32. class HueyIntegration(Integration):
  33. identifier = "huey"
  34. origin = f"auto.queue.{identifier}"
  35. @staticmethod
  36. def setup_once() -> None:
  37. patch_enqueue()
  38. patch_execute()
  39. def patch_enqueue() -> None:
  40. old_enqueue = Huey.enqueue
  41. @ensure_integration_enabled(HueyIntegration, old_enqueue)
  42. def _sentry_enqueue(
  43. self: "Huey", task: "Task"
  44. ) -> "Optional[Union[Result, ResultGroup]]":
  45. with sentry_sdk.start_span(
  46. op=OP.QUEUE_SUBMIT_HUEY,
  47. name=task.name,
  48. origin=HueyIntegration.origin,
  49. ):
  50. if not isinstance(task, PeriodicTask):
  51. # Attach trace propagation data to task kwargs. We do
  52. # not do this for periodic tasks, as these don't
  53. # really have an originating transaction.
  54. task.kwargs["sentry_headers"] = {
  55. BAGGAGE_HEADER_NAME: get_baggage(),
  56. SENTRY_TRACE_HEADER_NAME: get_traceparent(),
  57. }
  58. return old_enqueue(self, task)
  59. Huey.enqueue = _sentry_enqueue
  60. def _make_event_processor(task: "Any") -> "EventProcessor":
  61. def event_processor(event: "Event", hint: "Hint") -> "Optional[Event]":
  62. with capture_internal_exceptions():
  63. tags = event.setdefault("tags", {})
  64. tags["huey_task_id"] = task.id
  65. tags["huey_task_retry"] = task.default_retries > task.retries
  66. extra = event.setdefault("extra", {})
  67. extra["huey-job"] = {
  68. "task": task.name,
  69. "args": (
  70. task.args
  71. if should_send_default_pii()
  72. else SENSITIVE_DATA_SUBSTITUTE
  73. ),
  74. "kwargs": (
  75. task.kwargs
  76. if should_send_default_pii()
  77. else SENSITIVE_DATA_SUBSTITUTE
  78. ),
  79. "retry": (task.default_retries or 0) - task.retries,
  80. }
  81. return event
  82. return event_processor
  83. def _capture_exception(exc_info: "ExcInfo") -> None:
  84. scope = sentry_sdk.get_current_scope()
  85. if exc_info[0] in HUEY_CONTROL_FLOW_EXCEPTIONS:
  86. scope.transaction.set_status(SPANSTATUS.ABORTED)
  87. return
  88. scope.transaction.set_status(SPANSTATUS.INTERNAL_ERROR)
  89. event, hint = event_from_exception(
  90. exc_info,
  91. client_options=sentry_sdk.get_client().options,
  92. mechanism={"type": HueyIntegration.identifier, "handled": False},
  93. )
  94. scope.capture_event(event, hint=hint)
  95. def _wrap_task_execute(func: "F") -> "F":
  96. @ensure_integration_enabled(HueyIntegration, func)
  97. def _sentry_execute(*args: "Any", **kwargs: "Any") -> "Any":
  98. try:
  99. result = func(*args, **kwargs)
  100. except Exception:
  101. exc_info = sys.exc_info()
  102. _capture_exception(exc_info)
  103. reraise(*exc_info)
  104. return result
  105. return _sentry_execute # type: ignore
  106. def patch_execute() -> None:
  107. old_execute = Huey._execute
  108. @ensure_integration_enabled(HueyIntegration, old_execute)
  109. def _sentry_execute(
  110. self: "Huey", task: "Task", timestamp: "Optional[datetime]" = None
  111. ) -> "Any":
  112. with sentry_sdk.isolation_scope() as scope:
  113. with capture_internal_exceptions():
  114. scope._name = "huey"
  115. scope.clear_breadcrumbs()
  116. scope.add_event_processor(_make_event_processor(task))
  117. sentry_headers = task.kwargs.pop("sentry_headers", None)
  118. transaction = continue_trace(
  119. sentry_headers or {},
  120. name=task.name,
  121. op=OP.QUEUE_TASK_HUEY,
  122. source=TransactionSource.TASK,
  123. origin=HueyIntegration.origin,
  124. )
  125. transaction.set_status(SPANSTATUS.OK)
  126. if not getattr(task, "_sentry_is_patched", False):
  127. task.execute = _wrap_task_execute(task.execute)
  128. task._sentry_is_patched = True
  129. with sentry_sdk.start_transaction(transaction):
  130. return old_execute(self, task, timestamp)
  131. Huey._execute = _sentry_execute