Skip to content

Commit

Permalink
ref(browser): Improve setting of propagation scope for navigation spa…
Browse files Browse the repository at this point in the history
…ns (#15108)

Extracted this out of
#14955

Instead of registering a general hook & filtering there, we can just use
the `beforeSpanEnd` hook that we already have/use to do this instead.
  • Loading branch information
mydea authored Jan 22, 2025
1 parent 098f205 commit 580b8b5
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions packages/browser/src/tracing/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
getDynamicSamplingContextFromSpan,
getIsolationScope,
getLocationHref,
getRootSpan,
logger,
propagationContextFromHeaders,
registerSpanErrorInstrumentation,
Expand Down Expand Up @@ -276,6 +275,19 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
_collectWebVitals();
addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans });
setActiveIdleSpan(client, undefined);

// A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.
// Only when another navigation happens, we want to create a new trace.
// This way, e.g. errors that occur after the pageload span ended are still associated to the pageload trace.
const scope = getCurrentScope();
const oldPropagationContext = scope.getPropagationContext();

scope.setPropagationContext({
...oldPropagationContext,
traceId: idleSpan.spanContext().traceId,
sampled: spanIsSampled(idleSpan),
dsc: getDynamicSamplingContextFromSpan(span),
});
},
});
setActiveIdleSpan(client, idleSpan);
Expand Down Expand Up @@ -344,27 +356,6 @@ export const browserTracingIntegration = ((_options: Partial<BrowserTracingOptio
});
});

// A trace should to stay the consistent over the entire time span of one route.
// Therefore, when the initial pageload or navigation root span ends, we update the
// scope's propagation context to keep span-specific attributes like the `sampled` decision and
// the dynamic sampling context valid, even after the root span has ended.
// This ensures that the trace data is consistent for the entire duration of the route.
client.on('spanEnd', span => {
const op = spanToJSON(span).op;
if (span !== getRootSpan(span) || (op !== 'navigation' && op !== 'pageload')) {
return;
}

const scope = getCurrentScope();
const oldPropagationContext = scope.getPropagationContext();

scope.setPropagationContext({
...oldPropagationContext,
sampled: oldPropagationContext.sampled !== undefined ? oldPropagationContext.sampled : spanIsSampled(span),
dsc: oldPropagationContext.dsc || getDynamicSamplingContextFromSpan(span),
});
});

if (WINDOW.location) {
if (instrumentPageLoad) {
const origin = browserPerformanceTimeOrigin();
Expand Down

0 comments on commit 580b8b5

Please sign in to comment.