sentry-dotnet icon indicating copy to clipboard operation
sentry-dotnet copied to clipboard

Allow defining the "Active Span"

Open bruno-garcia opened this issue 3 years ago • 3 comments

Problem Statement

Integrations such as SentryHttpMesageHandler rely on

_hub.GetSpan()?.StartChild

to create a span. This on the Hub today is wired as:

        public ISpan? GetSpan() => Transaction?.GetLastActiveSpan() ?? Transaction;

This means I can't set a specific span to get returned from GetSpan. When parallelizing work, the parent/child relationship becomes messy since there are multiple spans "active" and relying on the root transaction isn't possible to find out which one it is.

Solution Brainstorm

When we're propagating the span explicitly downstream. A user can push a scope and set that new span as the active one. So integrations can find the correct parent span.

For example _hub.SetActiveSpan(span)

bruno-garcia avatar Aug 07 '22 22:08 bruno-garcia

@bruno-garcia so given adding SetActiveSpan to IHub would be a breaking change. is you plan to add this in the next major?

SimonCropp avatar Aug 19 '22 01:08 SimonCropp

Related to #1679.

KonstantinLukaschenko avatar Aug 29 '22 12:08 KonstantinLukaschenko

#1679 should be fixed after applying this enhancement to the AspNetCore integration. These two should be done together.

mattjohnsonpint avatar Sep 15 '22 21:09 mattjohnsonpint

Some time has passed and I recently took another look at this. We can achieve this goal without modifying the hub. Rather, we just need to implement setSpan on the scope as already defined in the Unified SDK with https://develop.sentry.dev/sdk/performance/#scope-changes

I propose rather than ISpan? GetSpan() and void SetSpan(ISpan?), we just use property conventions and go with ISpan? Span {get; set;}. We can obsolete and forward the existing Scope.GetSpan.

When used in conjunction with WithScope / WithScopeAsync (reintroduced in 3.31.0 with #2303), this make a much simpler way to achieve the same goal.

var span = SentrySdk.GetSpan();
Parallel.ForEach(items, item =>
{
    SentrySdk.WithScope(scope =>
    {
        scope.Span = span;

        // Do some work that might generate new child spans, etc.
        // They'll all be created from the span set on the scope.
    });
});

This works well for async also. See my notes and example here: https://github.com/getsentry/sentry-dotnet/issues/1679#issuecomment-1543274341

mattjohnsonpint avatar May 11 '23 03:05 mattjohnsonpint

Fixed in #2364

mattjohnsonpint avatar May 11 '23 04:05 mattjohnsonpint