Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 38 additions & 21 deletions sentry_sdk/integrations/dramatiq.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import json
import contextvars

import sentry_sdk
from sentry_sdk.consts import OP
from sentry_sdk.integrations import Integration
from sentry_sdk.integrations._wsgi_common import request_body_within_bounds
from sentry_sdk.tracing import TransactionSource
from sentry_sdk.utils import (
AnnotatedValue,
capture_internal_exceptions,
Expand All @@ -18,6 +21,7 @@

if TYPE_CHECKING:
from typing import Any, Callable, Dict, Optional, Union
from sentry_sdk.tracing import Transaction
from sentry_sdk._types import Event, Hint


Expand Down Expand Up @@ -85,20 +89,27 @@ class SentryMiddleware(Middleware): # type: ignore[misc]
DramatiqIntegration.
"""

# type: contextvars.ContextVar[Transaction]
_transaction = contextvars.ContextVar("_transaction", default=None)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we using a ContextVar here, instead of just a simple instance variable on the SentryMiddleware?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To isolate variable between threads:

  1. Dramatiq can be started in multithreading mode:
    dramatiq --processes 1 --threads 5 ...
  2. And I was inspired by official middleware:
    CurrentMessageMiddleware

I will try recheck if it's actually needed

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed.
One SentryMiddleware instance will be shared between threads. So, isolating is necessary.
Previous (actually current) realisation adds _scope_manager to message, but I think ContextVar is much cleaner solution


def before_process_message(self, broker, message):
# type: (Broker, Message) -> None
integration = sentry_sdk.get_client().get_integration(DramatiqIntegration)
if integration is None:
return

message._scope_manager = sentry_sdk.new_scope()
message._scope_manager.__enter__()

scope = sentry_sdk.get_current_scope()
scope.set_transaction_name(message.actor_name)
scope.set_extra("dramatiq_message_id", message.message_id)
scope.add_event_processor(_make_message_event_processor(message, integration))

transaction = sentry_sdk.start_transaction(
name=message.actor_name,
op=OP.QUEUE_PROCESS,
source=TransactionSource.TASK,
)
transaction.__enter__()
self._transaction.set(transaction)

def after_process_message(self, broker, message, *, result=None, exception=None):
# type: (Broker, Message, Any, Optional[Any], Optional[Exception]) -> None
integration = sentry_sdk.get_client().get_integration(DramatiqIntegration)
Expand All @@ -108,23 +119,29 @@ def after_process_message(self, broker, message, *, result=None, exception=None)
actor = broker.get_actor(message.actor_name)
throws = message.options.get("throws") or actor.options.get("throws")

try:
if (
exception is not None
and not (throws and isinstance(exception, throws))
and not isinstance(exception, Retry)
):
event, hint = event_from_exception(
exception,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": DramatiqIntegration.identifier,
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
finally:
message._scope_manager.__exit__(None, None, None)
transaction = self._transaction.get()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Dramatiq Integration Transaction Handling Issues

The Dramatiq integration has two issues. after_process_message can raise a LookupError when retrieving the transaction from ContextVar if before_process_message returned early (e.g., integration is None), as the transaction was never set. Additionally, the transaction is created with continue_trace(op=OP.QUEUE_TASK_DRAMATIQ) but then immediately passed to sentry_sdk.start_transaction(op=OP.QUEUE_PROCESS), overwriting the operation type and incorrectly mixing API calls.

Fix in Cursor Fix in Web


is_event_capture_required = (
exception is not None
and not (throws and isinstance(exception, throws))
and not isinstance(exception, Retry)
)
if not is_event_capture_required:
# normal transaction finish
transaction.__exit__(None, None, None)
return

event, hint = event_from_exception(
exception,
client_options=sentry_sdk.get_client().options,
mechanism={
"type": DramatiqIntegration.identifier,
"handled": False,
},
)
sentry_sdk.capture_event(event, hint=hint)
# transaction error
transaction.__exit__(type(exception), exception, None)


def _make_message_event_processor(message, integration):
Expand Down
Loading