Skip to content

Commit 12aa51e

Browse files
aticies3rius
authored andcommitted
fix opentelemetry context detach issues
1 parent ef92b9e commit 12aa51e

1 file changed

Lines changed: 23 additions & 34 deletions

File tree

‎taskiq/middlewares/opentelemetry_middleware.py‎

Lines changed: 23 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -312,40 +312,6 @@ def pre_execute(self, message: TaskiqMessage) -> TaskiqMessage:
312312
)
313313
return message
314314

315-
def post_save( # pylint: disable=R6301
316-
self,
317-
message: TaskiqMessage,
318-
result: TaskiqResult[T],
319-
) -> None:
320-
"""
321-
This function closes span from `pre_execute`.
322-
323-
:param message: received message.
324-
:param result: result of the execution.
325-
"""
326-
logger.debug("post_execute task_id=%s", message.task_id)
327-
328-
# retrieve and finish the Span
329-
ctx = retrieve_context(message)
330-
331-
if ctx is None:
332-
logger.warning("no existing span found for task_id=%s", message.task_id)
333-
return
334-
335-
span, activation, token = ctx
336-
337-
if span.is_recording():
338-
span.set_attribute(_TASK_TAG_KEY, _TASK_EXECUTE)
339-
set_attributes_from_context(span, message.labels)
340-
span.set_attribute(_TASK_NAME_KEY, message.task_name)
341-
342-
activation.__exit__(None, None, None)
343-
detach_context(message)
344-
# if the process sending the task is not instrumented
345-
# there's no incoming context and no token to detach
346-
if token is not None:
347-
context_api.detach(token) # type: ignore[arg-type]
348-
349315
def on_error(
350316
self,
351317
message: TaskiqMessage,
@@ -399,6 +365,8 @@ def post_execute(
399365
:param message: received message.
400366
:param result: result of the execution.
401367
"""
368+
logger.debug("post_execute task_id=%s", message.task_id)
369+
402370
if result.is_err:
403371
retry_on_error = message.labels.get("retry_on_error")
404372
if isinstance(retry_on_error, str):
@@ -441,3 +409,24 @@ def post_execute(
441409
-1,
442410
attributes={"task_name": message.task_name},
443411
)
412+
413+
# retrieve and finish the Span
414+
ctx = retrieve_context(message)
415+
416+
if ctx is None:
417+
logger.warning("no existing span found for task_id=%s", message.task_id)
418+
return
419+
420+
span, activation, token = ctx
421+
422+
if span.is_recording():
423+
span.set_attribute(_TASK_TAG_KEY, _TASK_EXECUTE)
424+
set_attributes_from_context(span, message.labels)
425+
span.set_attribute(_TASK_NAME_KEY, message.task_name)
426+
427+
activation.__exit__(None, None, None)
428+
detach_context(message)
429+
# if the process sending the task is not instrumented
430+
# there's no incoming context and no token to detach
431+
if token is not None:
432+
context_api.detach(token) # type: ignore[arg-type]

0 commit comments

Comments
 (0)