@@ -61,7 +61,6 @@ def sentry_build_tracer(name, task, *args, **kwargs):
6161 # short-circuits to task.run if it thinks it's safe.
6262 task .__call__ = _wrap_task_call (task , task .__call__ )
6363 task .run = _wrap_task_call (task , task .run )
64- task .apply_async = _wrap_apply_async (task , task .apply_async )
6564
6665 # `build_tracer` is apparently called for every task
6766 # invocation. Can't wrap every celery task for every invocation
@@ -72,6 +71,10 @@ def sentry_build_tracer(name, task, *args, **kwargs):
7271
7372 trace .build_tracer = sentry_build_tracer
7473
74+ from celery .app .task import Task # type: ignore
75+
76+ Task .apply_async = _wrap_apply_async (Task .apply_async )
77+
7578 _patch_worker_exit ()
7679
7780 # This logger logs every status of every task that ran on the worker.
@@ -85,30 +88,31 @@ def sentry_build_tracer(name, task, *args, **kwargs):
8588 ignore_logger ("celery.redirected" )
8689
8790
88- def _wrap_apply_async (task , f ):
89- # type: (Any, F) -> F
91+ def _wrap_apply_async (f ):
92+ # type: (F) -> F
9093 @wraps (f )
9194 def apply_async (* args , ** kwargs ):
9295 # type: (*Any, **Any) -> Any
9396 hub = Hub .current
9497 integration = hub .get_integration (CeleryIntegration )
9598 if integration is not None and integration .propagate_traces :
96- with hub .start_span (op = "celery.submit" , description = task .name ):
99+ with hub .start_span (op = "celery.submit" , description = args [ 0 ] .name ):
97100 with capture_internal_exceptions ():
98101 headers = dict (hub .iter_trace_propagation_headers ())
102+
99103 if headers :
100- kwarg_headers = kwargs .setdefault ("headers" , {})
104+ # Note: kwargs can contain headers=None, so no setdefault!
105+ # Unsure which backend though.
106+ kwarg_headers = kwargs .get ("headers" ) or {}
101107 kwarg_headers .update (headers )
102108
103109 # https://github.com/celery/celery/issues/4875
104110 #
105111 # Need to setdefault the inner headers too since other
106112 # tracing tools (dd-trace-py) also employ this exact
107113 # workaround and we don't want to break them.
108- #
109- # This is not reproducible outside of AMQP, therefore no
110- # tests!
111114 kwarg_headers .setdefault ("headers" , {}).update (headers )
115+ kwargs ["headers" ] = kwarg_headers
112116
113117 return f (* args , ** kwargs )
114118 else :
0 commit comments