Skip to content

feat(nexjs): Sample out low-quality spans on older Next.js versions #11722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
28 changes: 28 additions & 0 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import type {
SessionAggregates,
SeverityLevel,
Span,
SpanAttributes,
SpanContextData,
StartSpanOptions,
TransactionEvent,
Transport,
Expand Down Expand Up @@ -416,6 +418,20 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
callback: (feedback: FeedbackEvent, options?: { includeReplay: boolean }) => void,
): void;

/** @inheritdoc */
public on(
hook: 'afterSampling',
callback: (
samplingData: {
spanAttributes: SpanAttributes;
spanName: string;
parentSampled?: boolean;
parentContext?: SpanContextData;
},
samplingDecision: { decision: boolean },
) => void,
): void;

/** @inheritdoc */
public on(
hook: 'startPageLoadSpan',
Expand All @@ -442,6 +458,18 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
this._hooks[hook].push(callback);
}

/** @inheritdoc */
public emit(
hook: 'afterSampling',
samplingData: {
spanAttributes: SpanAttributes;
spanName: string;
parentSampled?: boolean;
parentContext?: SpanContextData;
},
samplingDecision: { decision: boolean },
): void;

/** @inheritdoc */
public emit(hook: 'spanStart', span: Span): void;

Expand Down
32 changes: 31 additions & 1 deletion packages/nextjs/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ const globalWithInjectedValues = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
__sentryRewritesTunnelPath__?: string;
};

// https://github.com/lforst/nextjs-fork/blob/9051bc44d969a6e0ab65a955a2fc0af522a83911/packages/next/src/server/lib/trace/constants.ts#L11
const NEXTJS_SPAN_NAME_PREFIXES = [
'BaseServer',
'LoadComponents',
'NextServer',
'createServer',
'startServer',
'NextNodeServer',
'Render',
'AppRender',
'Router',
'Node',
'AppRouteRouteHandlers',
'ResolveMetadata',
];

/**
* A passthrough error boundary for the server that doesn't depend on any react. Error boundaries don't catch SSR errors
* so they should simply be a passthrough.
Expand Down Expand Up @@ -90,7 +106,7 @@ export function init(options: NodeOptions): void {
customDefaultIntegrations.push(distDirRewriteFramesIntegration({ distDirName }));
}

const opts = {
const opts: NodeOptions = {
environment: process.env.SENTRY_ENVIRONMENT || getVercelEnv(false) || process.env.NODE_ENV,
defaultIntegrations: customDefaultIntegrations,
...options,
Expand All @@ -113,6 +129,20 @@ export function init(options: NodeOptions): void {

nodeInit(opts);

const client = getClient();
client?.on('afterSampling', ({ spanAttributes, spanName, parentSampled, parentContext }, samplingDecision) => {
// If we encounter a span emitted by Next.js, we do not want to sample it
// The reason for this is that the data quality of the spans varies, it is different per version of Next,
// and we need to keep our manual instrumentation around for the edge runtime anyhow.
// BUT we only do this if we don't have a parent span with a sampling decision yet (or if the parent is remote)
if (
(spanAttributes['next.span_type'] || NEXTJS_SPAN_NAME_PREFIXES.includes(spanName.split('.')[0])) &&
(typeof parentSampled !== 'boolean' || parentContext?.isRemote)
) {
samplingDecision.decision = false;
}
});

addEventProcessor(
Object.assign(
(event => {
Expand Down
24 changes: 15 additions & 9 deletions packages/opentelemetry/src/sampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,7 @@ export class SentrySampler implements Sampler {

const parentSampled = parentSpan ? getParentSampled(parentSpan, traceId, spanName) : undefined;

// If we encounter a span emitted by Next.js, we do not want to sample it
// The reason for this is that the data quality of the spans varies, it is different per version of Next,
// and we need to keep our manual instrumentation around for the edge runtime anyhow.
// BUT we only do this if we don't have a parent span with a sampling decision yet (or if the parent is remote)
if (spanAttributes['next.span_type'] && (typeof parentSampled !== 'boolean' || parentContext?.isRemote)) {
return { decision: SamplingDecision.NOT_RECORD, traceState: traceState };
}

const [sampled, sampleRate] = sampleSpan(options, {
const [samplerDecision, sampleRate] = sampleSpan(options, {
name: spanName,
attributes: spanAttributes,
transactionContext: {
Expand All @@ -82,6 +74,20 @@ export class SentrySampler implements Sampler {
parentSampled,
});

const mutableSamplingDecision = { decision: samplerDecision };
this._client.emit(
'afterSampling',
{
spanAttributes: spanAttributes,
spanName: spanName,
parentSampled: parentSampled,
parentContext: parentContext,
},
mutableSamplingDecision,
);

const sampled = mutableSamplingDecision.decision;

const attributes: Attributes = {
[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
};
Expand Down
28 changes: 27 additions & 1 deletion packages/types/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { Scope } from './scope';
import type { SdkMetadata } from './sdkmetadata';
import type { Session, SessionAggregates } from './session';
import type { SeverityLevel } from './severity';
import type { Span } from './span';
import type { Span, SpanAttributes, SpanContextData } from './span';
import type { StartSpanOptions } from './startSpanOptions';
import type { Transport, TransportMakeRequestResponse } from './transport';

Expand Down Expand Up @@ -178,6 +178,20 @@ export interface Client<O extends ClientOptions = ClientOptions> {
*/
on(hook: 'spanStart', callback: (span: Span) => void): void;

/** TODO */
on(
hook: 'afterSampling',
callback: (
samplingData: {
spanAttributes: SpanAttributes;
spanName: string;
parentSampled?: boolean;
parentContext?: SpanContextData;
},
samplingDecision: { decision: boolean },
) => void,
): void;

/**
* Register a callback for whenever a span is ended.
* Receives the span as argument.
Expand Down Expand Up @@ -262,6 +276,18 @@ export interface Client<O extends ClientOptions = ClientOptions> {
/** Fire a hook whener a span starts. */
emit(hook: 'spanStart', span: Span): void;

/** TODO */
emit(
hook: 'afterSampling',
samplingData: {
spanAttributes: SpanAttributes;
spanName: string;
parentSampled?: boolean;
parentContext?: SpanContextData;
},
samplingDecision: { decision: boolean },
): void;

/** Fire a hook whener a span ends. */
emit(hook: 'spanEnd', span: Span): void;

Expand Down