Skip to content

Commit 1646f0b

Browse files
author
Luca Forstner
committed
Write and use sample rand on propagation context
1 parent a83a511 commit 1646f0b

File tree

14 files changed

+87
-40
lines changed

14 files changed

+87
-40
lines changed

docs/migration/v8-to-v9.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ Sentry.init({
186186
- The `addRequestDataToEvent` method has been removed. Use `httpRequestToRequestData` instead and put the resulting object directly on `event.request`.
187187
- The `extractPathForTransaction` method has been removed. There is no replacement.
188188
- The `addNormalizedRequestDataToEvent` method has been removed. Use `httpRequestToRequestData` instead and put the resulting object directly on `event.request`.
189+
- A `sampleRand` field on `PropagationContext` is now required. This is relevant if you used `scope.setPropagationContext(...)`
189190

190191
#### Other/Internal Changes
191192

packages/browser/src/tracing/browserTracingIntegration.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -452,8 +452,8 @@ export function startBrowserTracingPageLoadSpan(
452452
* This will only do something if a browser tracing integration has been setup.
453453
*/
454454
export function startBrowserTracingNavigationSpan(client: Client, spanOptions: StartSpanOptions): Span | undefined {
455-
getIsolationScope().setPropagationContext({ traceId: generateTraceId() });
456-
getCurrentScope().setPropagationContext({ traceId: generateTraceId() });
455+
getIsolationScope().setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
456+
getCurrentScope().setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
457457

458458
client.emit('startNavigationSpan', spanOptions);
459459

packages/core/src/scope.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ export class Scope {
164164
this._sdkProcessingMetadata = {};
165165
this._propagationContext = {
166166
traceId: generateTraceId(),
167+
sampleRand: Math.random(),
167168
};
168169
}
169170

@@ -456,7 +457,7 @@ export class Scope {
456457
this._session = undefined;
457458
_setSpanForScope(this, undefined);
458459
this._attachments = [];
459-
this.setPropagationContext({ traceId: generateTraceId() });
460+
this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });
460461

461462
this._notifyScopeListeners();
462463
return this;

packages/core/src/tracing/dynamicSamplingContext.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ export function getDynamicSamplingContextFromSpan(span: Span): Readonly<Partial<
116116
// So we end up with an active span that is not sampled (neither positively nor negatively)
117117
if (hasTracingEnabled()) {
118118
dsc.sampled = String(spanIsSampled(rootSpan));
119+
// TODO(lforst): Grab scope off of root span and put sample_rand on dsc
119120
}
120121

121122
client.emit('createDsc', dsc, rootSpan);

packages/core/src/tracing/sampling.ts

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { Options, SamplingContext } from '../types-hoist';
22

3-
import { getIsolationScope } from '../currentScopes';
43
import { DEBUG_BUILD } from '../debug-build';
54
import { logger } from '../utils-hoist/logger';
65
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
@@ -15,26 +14,20 @@ import { parseSampleRate } from '../utils/parseSampleRate';
1514
export function sampleSpan(
1615
options: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'>,
1716
samplingContext: SamplingContext,
17+
sampleRand: number,
1818
): [sampled: boolean, sampleRate?: number] {
1919
// nothing to do if tracing is not enabled
2020
if (!hasTracingEnabled(options)) {
2121
return [false];
2222
}
2323

24-
const normalizedRequest = getIsolationScope().getScopeData().sdkProcessingMetadata.normalizedRequest;
25-
26-
const enhancedSamplingContext = {
27-
...samplingContext,
28-
normalizedRequest: samplingContext.normalizedRequest || normalizedRequest,
29-
};
30-
3124
// we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should
3225
// work; prefer the hook if so
3326
let sampleRate;
3427
if (typeof options.tracesSampler === 'function') {
35-
sampleRate = options.tracesSampler(enhancedSamplingContext);
36-
} else if (enhancedSamplingContext.parentSampled !== undefined) {
37-
sampleRate = enhancedSamplingContext.parentSampled;
28+
sampleRate = options.tracesSampler(samplingContext);
29+
} else if (samplingContext.parentSampled !== undefined) {
30+
sampleRate = samplingContext.parentSampled;
3831
} else if (typeof options.tracesSampleRate !== 'undefined') {
3932
sampleRate = options.tracesSampleRate;
4033
} else {
@@ -66,7 +59,7 @@ export function sampleSpan(
6659

6760
// Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
6861
// a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
69-
const shouldSample = Math.random() < parsedSampleRate;
62+
const shouldSample = sampleRand < parsedSampleRate;
7063

7164
// if we're not going to keep it, we're done
7265
if (!shouldSample) {

packages/core/src/tracing/trace.ts

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,10 @@ export function suppressTracing<T>(callback: () => T): T {
279279
*/
280280
export function startNewTrace<T>(callback: () => T): T {
281281
return withScope(scope => {
282-
scope.setPropagationContext({ traceId: generateTraceId() });
282+
scope.setPropagationContext({
283+
traceId: generateTraceId(),
284+
sampleRand: Math.random(),
285+
});
283286
DEBUG_BUILD && logger.info(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);
284287
return withActiveSpan(null, callback);
285288
});
@@ -402,17 +405,23 @@ function _startRootSpan(spanArguments: SentrySpanArguments, scope: Scope, parent
402405
const options: Partial<ClientOptions> = client?.getOptions() || {};
403406

404407
const { name = '', attributes } = spanArguments;
408+
const sampleRand = scope.getPropagationContext().sampleRand;
405409
const [sampled, sampleRate] = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY]
406410
? [false]
407-
: sampleSpan(options, {
408-
name,
409-
parentSampled,
410-
attributes,
411-
transactionContext: {
411+
: sampleSpan(
412+
options,
413+
{
412414
name,
413415
parentSampled,
416+
attributes,
417+
transactionContext: {
418+
name,
419+
parentSampled,
420+
},
421+
// parentSampleRate: 'TODO',
414422
},
415-
});
423+
sampleRand,
424+
);
416425

417426
const rootSpan = new SentrySpan({
418427
...spanArguments,

packages/core/src/types-hoist/envelope.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export type DynamicSamplingContext = {
2323
transaction?: string;
2424
replay_id?: string;
2525
sampled?: string;
26+
sample_rand?: string;
2627
};
2728

2829
// https://github.com/getsentry/relay/blob/311b237cd4471042352fa45e7a0824b8995f216f/relay-server/src/envelope.rs#L154

packages/core/src/types-hoist/samplingcontext.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ export interface SamplingContext extends CustomSamplingContext {
2929
*/
3030
parentSampled?: boolean;
3131

32+
/**
33+
* Sample rate that is coming from an incoming trace (if there is one).
34+
*/
35+
parentSampleRate?: number;
36+
3237
/**
3338
* Object representing the URL of the current page or worker script. Passed by default when using the `BrowserTracing`
3439
* integration.

packages/core/src/types-hoist/tracing.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ export interface PropagationContext {
1616
*/
1717
traceId: string;
1818

19+
/**
20+
* TODO
21+
*/
22+
sampleRand: number;
23+
1924
/**
2025
* Represents the sampling decision of the incoming trace.
2126
*

packages/core/src/utils-hoist/propagationContext.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { uuid4 } from './misc';
99
export function generatePropagationContext(): PropagationContext {
1010
return {
1111
traceId: generateTraceId(),
12+
sampleRand: Math.random(),
1213
};
1314
}
1415

0 commit comments

Comments
 (0)