Skip to content
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

Add transaction source for dynamic sampling #2454

Merged
merged 7 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Bump JavaScript SDK from v7.9.0 to v7.12.1 ([#2451](https://github.com/getsentry/sentry-react-native/pull/2451))
- [changelog](https://github.com/getsentry/sentry-javascript/blob/master/CHANGELOG.md#7121)
- [diff](https://github.com/getsentry/sentry-javascript/compare/7.9.0...7.12.1)
- Add Transaction Source for Dynamic Sampling Context ([#2454](https://github.com/getsentry/sentry-react-native/pull/2454))

## 4.2.4

Expand Down
56 changes: 34 additions & 22 deletions src/js/tracing/reactnativenavigation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Transaction as TransactionType } from '@sentry/types';
import { Transaction as TransactionType, TransactionContext } from '@sentry/types';
import { logger } from '@sentry/utils';
import { EmitterSubscription } from 'react-native';

Expand All @@ -8,7 +8,7 @@ import {
TransactionCreator,
} from './routingInstrumentation';
import { BeforeNavigate, RouteChangeContextData } from './types';
import { getBlankTransactionContext } from './utils';
import { defaultTransactionSource, getBlankTransactionContext } from './utils';

interface ReactNativeNavigationOptions {
routeChangeTimeoutMs: number;
Expand Down Expand Up @@ -171,29 +171,16 @@ export class ReactNativeNavigationInstrumentation extends InternalRoutingInstrum
data,
};

let finalContext = this._beforeNavigate?.(updatedContext);

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[${ReactNativeNavigationInstrumentation.name}] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...updatedContext,
sampled: false,
};
}
const finalContext = this._prepareFinalContext(updatedContext);
this._latestTransaction.updateWithContext(finalContext);

if (finalContext.sampled === false) {
logger.log(
`[${ReactNativeNavigationInstrumentation.name}] Will not send transaction "${finalContext.name}" due to beforeNavigate.`
);
}
const isCustomName = updatedContext.name !== finalContext.name;
this._latestTransaction.setName(
finalContext.name,
isCustomName ? 'custom' : defaultTransactionSource,
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved
);

this._latestTransaction.updateWithContext(finalContext);
this._onConfirmRoute?.(finalContext);

this._prevComponentEvent = event;
} else {
this._discardLatestTransaction();
Expand All @@ -203,6 +190,31 @@ export class ReactNativeNavigationInstrumentation extends InternalRoutingInstrum
}
}

/** Creates final transaction context before confirmation */
private _prepareFinalContext(updatedContext: TransactionContext): TransactionContext {
let finalContext = this._beforeNavigate?.({ ...updatedContext });

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[${ReactNativeNavigationInstrumentation.name}] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...updatedContext,
sampled: false,
};
}

if (finalContext.sampled === false) {
logger.log(
`[${ReactNativeNavigationInstrumentation.name}] Will not send transaction "${finalContext.name}" due to beforeNavigate.`
);
}

return finalContext;
}

/** Cancels the latest transaction so it does not get sent to Sentry. */
private _discardLatestTransaction(): void {
if (this._latestTransaction) {
Expand Down
63 changes: 38 additions & 25 deletions src/js/tracing/reactnavigation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable max-lines */
import { Transaction as TransactionType } from '@sentry/types';
import { Transaction as TransactionType, TransactionContext } from '@sentry/types';
import { getGlobalObject, logger } from '@sentry/utils';

import {
Expand All @@ -12,7 +12,7 @@ import {
ReactNavigationTransactionContext,
RouteChangeContextData,
} from './types';
import { getBlankTransactionContext } from './utils';
import { defaultTransactionSource, getBlankTransactionContext } from './utils';

export interface NavigationRoute {
name: string;
Expand Down Expand Up @@ -228,31 +228,15 @@ export class ReactNavigationInstrumentation extends InternalRoutingInstrumentati
data,
};

let finalContext = this._beforeNavigate?.(updatedContext);

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[ReactNavigationInstrumentation] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...updatedContext,
sampled: false,
};
}
const finalContext = this._prepareFinalContext(updatedContext);
this._latestTransaction.updateWithContext(finalContext);

// Note: finalContext.sampled will be false at this point only if the user sets it to be so in beforeNavigate.
if (finalContext.sampled === false) {
logger.log(
`[ReactNavigationInstrumentation] Will not send transaction "${finalContext.name}" due to beforeNavigate.`
);
} else {
// Clear the timeout so the transaction does not get cancelled.
this._clearStateChangeTimeout();
}
const isCustomName = updatedContext.name !== finalContext.name;
this._latestTransaction.setName(
finalContext.name,
isCustomName ? 'custom' : defaultTransactionSource,
);

this._latestTransaction.updateWithContext(finalContext);
this._onConfirmRoute?.(finalContext);
}

Expand All @@ -265,6 +249,35 @@ export class ReactNavigationInstrumentation extends InternalRoutingInstrumentati
this._latestTransaction = undefined;
}

/** Creates final transaction context before confirmation */
private _prepareFinalContext(updatedContext: TransactionContext): TransactionContext {
let finalContext = this._beforeNavigate?.({ ...updatedContext });

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[ReactNavigationInstrumentation] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...updatedContext,
sampled: false,
};
}

// Note: finalContext.sampled will be false at this point only if the user sets it to be so in beforeNavigate.
if (finalContext.sampled === false) {
logger.log(
`[ReactNavigationInstrumentation] Will not send transaction "${finalContext.name}" due to beforeNavigate.`
);
} else {
// Clear the timeout so the transaction does not get cancelled.
this._clearStateChangeTimeout();
}

return finalContext;
}

/** Pushes a recent route key, and removes earlier routes when there is greater than the max length */
private _pushRecentRouteKey = (key: string): void => {
this._recentRouteKeys.push(key);
Expand Down
54 changes: 35 additions & 19 deletions src/js/tracing/reactnavigationv4.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable max-lines */
import { Transaction } from '@sentry/types';
import { Transaction, TransactionContext } from '@sentry/types';
import { getGlobalObject, logger } from '@sentry/utils';

import {
Expand All @@ -12,6 +12,7 @@ import {
ReactNavigationTransactionContext,
RouteChangeContextData,
} from './types';
import { defaultTransactionSource } from './utils';

export interface NavigationRouteV4 {
routeName: string;
Expand Down Expand Up @@ -230,27 +231,16 @@ class ReactNavigationV4Instrumentation extends InternalRoutingInstrumentation {
};
}

let finalContext = this._beforeNavigate?.(mergedContext);

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[ReactNavigationV4Instrumentation] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...mergedContext,
sampled: false,
};
}

if (finalContext.sampled === false) {
this._onBeforeNavigateNotSampled(finalContext.name);
}
const finalContext = this._prepareFinalContext(mergedContext);

if (updateLatestTransaction && this._latestTransaction) {
// Update the latest transaction instead of calling onRouteWillChange
this._latestTransaction.updateWithContext(finalContext);
const isCustomName = mergedContext.name !== finalContext.name;
this._latestTransaction.setName(
finalContext.name,
isCustomName ? 'custom' : defaultTransactionSource,
);
} else {
this._latestTransaction = this.onRouteWillChange(finalContext);
}
Expand All @@ -262,6 +252,29 @@ class ReactNavigationV4Instrumentation extends InternalRoutingInstrumentation {
}
}

/** Creates final transaction context before confirmation */
private _prepareFinalContext(mergedContext: TransactionContext): TransactionContext {
let finalContext = this._beforeNavigate?.({ ...mergedContext });

// This block is to catch users not returning a transaction context
if (!finalContext) {
logger.error(
`[ReactNavigationV4Instrumentation] beforeNavigate returned ${finalContext}, return context.sampled = false to not send transaction.`
);

finalContext = {
...mergedContext,
sampled: false,
};
}

if (finalContext.sampled === false) {
this._onBeforeNavigateNotSampled(finalContext.name);
}

return finalContext;
}

/**
* Gets the transaction context for a `NavigationRouteV4`
*/
Expand Down Expand Up @@ -345,14 +358,17 @@ class ReactNavigationV4Instrumentation extends InternalRoutingInstrumentation {
}
}

const INITIAL_TRANSACTION_CONTEXT_V4 = {
const INITIAL_TRANSACTION_CONTEXT_V4: TransactionContext = {
name: 'App Launch',
op: 'navigation',
tags: {
'routing.instrumentation':
ReactNavigationV4Instrumentation.instrumentationName,
},
data: {},
metadata: {
source: 'view',
},
};

export { ReactNavigationV4Instrumentation, INITIAL_TRANSACTION_CONTEXT_V4 };
7 changes: 6 additions & 1 deletion src/js/tracing/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { IdleTransaction, Span, Transaction } from '@sentry/tracing';
import { TransactionContext } from '@sentry/types';
import { TransactionContext, TransactionSource } from '@sentry/types';
import { timestampInSeconds } from '@sentry/utils';

export const defaultTransactionSource: TransactionSource = 'view';
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved

export const getBlankTransactionContext = (
name: string
): TransactionContext => {
Expand All @@ -12,6 +14,9 @@ export const getBlankTransactionContext = (
'routing.instrumentation': name,
},
data: {},
metadata: {
source: defaultTransactionSource,
},
};
};

Expand Down
3 changes: 3 additions & 0 deletions test/tracing/reactnativenavigation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ describe('React Native Navigation Instrumentation', () => {
},
previousRoute: null,
});
expect(mockTransaction.metadata.source).toBe('view');
});

test('Transaction context is changed with beforeNavigate', () => {
Expand Down Expand Up @@ -144,6 +145,7 @@ describe('React Native Navigation Instrumentation', () => {
},
previousRoute: null,
});
expect(mockTransaction.metadata.source).toBe('custom');
});

test('Transaction not sent on a cancelled route change', () => {
Expand Down Expand Up @@ -258,6 +260,7 @@ describe('React Native Navigation Instrumentation', () => {
expect(confirmedContext).toBeDefined();
if (confirmedContext) {
expect(confirmedContext.name).toBe(mockEvent2.componentName);
expect(confirmedContext.metadata).toBeUndefined();
expect(confirmedContext.data).toBeDefined();
if (confirmedContext.data) {
expect(confirmedContext.data.route.name).toBe(
Expand Down
4 changes: 4 additions & 0 deletions test/tracing/reactnavigation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ describe('ReactNavigationInstrumentation', () => {
},
previousRoute: null,
});
expect(mockTransaction.metadata.source).toBe('view');
});

test('transaction sent on navigation', async () => {
Expand Down Expand Up @@ -140,6 +141,7 @@ describe('ReactNavigationInstrumentation', () => {
params: {},
},
});
expect(mockTransaction.metadata.source).toBe('view');

resolve();
}, 50);
Expand Down Expand Up @@ -192,6 +194,7 @@ describe('ReactNavigationInstrumentation', () => {
expect(mockTransaction.sampled).toBe(false);
expect(mockTransaction.name).toBe('New Name');
expect(mockTransaction.description).toBe('Description');
expect(mockTransaction.metadata.source).toBe('custom');
resolve();
}, 50);
});
Expand Down Expand Up @@ -488,6 +491,7 @@ describe('ReactNavigationInstrumentation', () => {
expect(confirmedContext).toBeDefined();
if (confirmedContext) {
expect(confirmedContext.name).toBe(route2.name);
expect(confirmedContext.metadata).toBeUndefined();
expect(confirmedContext.data).toBeDefined();
if (confirmedContext.data) {
expect(confirmedContext.data.route.name).toBe(route2.name);
Expand Down
4 changes: 4 additions & 0 deletions test/tracing/reactnavigationv4.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ describe('ReactNavigationV4Instrumentation', () => {
previousRoute: null,
});
expect(mockTransaction.sampled).toBe(true);
expect(mockTransaction.metadata.source).toBe('view');
});

test('transaction sent on navigation', () => {
Expand Down Expand Up @@ -199,6 +200,7 @@ describe('ReactNavigationV4Instrumentation', () => {
});

expect(mockTransaction.sampled).toBe(true);
expect(mockTransaction.metadata.source).toBe('view');
});

test('transaction context changed with beforeNavigate', () => {
Expand Down Expand Up @@ -262,6 +264,7 @@ describe('ReactNavigationV4Instrumentation', () => {
});

expect(mockTransaction.sampled).toBe(false);
expect(mockTransaction.metadata.source).toBe('custom');
});

test('transaction not attached on a cancelled navigation', () => {
Expand Down Expand Up @@ -498,6 +501,7 @@ describe('ReactNavigationV4Instrumentation', () => {
if (confirmedContext) {
expect(confirmedContext.name).toBe(route2.routeName);
expect(confirmedContext.data).toBeDefined();
expect(confirmedContext.metadata).toBeUndefined();
krystofwoldrich marked this conversation as resolved.
Show resolved Hide resolved
if (confirmedContext.data) {
expect(confirmedContext.data.route.name).toBe(route2.routeName);
expect(confirmedContext.data.previousRoute).toBeDefined();
Expand Down