Skip to content

feat(core): Allow custom tracing implementations #11003

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 1 commit into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions packages/core/src/asyncContext.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { Hub, Integration } from '@sentry/types';
import type { Scope } from '@sentry/types';
import { GLOBAL_OBJ } from '@sentry/utils';
import type { startInactiveSpan, startSpan, startSpanManual, withActiveSpan } from './tracing/trace';
import type { getActiveSpan } from './utils/spanUtils';

/**
* @private Private API with no semver guarantees!
Expand Down Expand Up @@ -42,6 +44,24 @@ export interface AsyncContextStrategy {
* Get the currently active isolation scope.
*/
getIsolationScope: () => Scope;

// OPTIONAL: Custom tracing methods
// These are used so that we can provide OTEL-based implementations

/** Start an active span. */
startSpan?: typeof startSpan;

/** Start an inactive span. */
startInactiveSpan?: typeof startInactiveSpan;

/** Start an active manual span. */
startSpanManual?: typeof startSpanManual;

/** Get the currently active span. */
getActiveSpan?: typeof getActiveSpan;

/** Make a span the active span in the context of the callback. */
withActiveSpan?: typeof withActiveSpan;
}

/**
Expand Down
21 changes: 1 addition & 20 deletions packages/core/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,16 @@ import type {
FinishedCheckIn,
MonitorConfig,
Primitive,
Scope as ScopeInterface,
Session,
SessionContext,
SeverityLevel,
Span,
TransactionContext,
User,
} from '@sentry/types';
import { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';

import { DEFAULT_ENVIRONMENT } from './constants';
import { getClient, getCurrentScope, getIsolationScope, withScope } from './currentScopes';
import { getClient, getCurrentScope, getIsolationScope } from './currentScopes';
import { DEBUG_BUILD } from './debug-build';
import type { Hub } from './hub';
import { getCurrentHub } from './hub';
Expand Down Expand Up @@ -126,23 +124,6 @@ export function setUser(user: User | null): ReturnType<Hub['setUser']> {
getIsolationScope().setUser(user);
}

/**
* Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
* passed `null` to start an entirely new span tree.
*
* @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
* spans started within the callback will not be attached to a parent span.
* @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
* @returns the value returned from the provided callback function.
*/
export function withActiveSpan<T>(span: Span | null, callback: (scope: ScopeInterface) => T): T {
return withScope(scope => {
// eslint-disable-next-line deprecation/deprecation
scope.setSpan(span || undefined);
return callback(scope);
});
}

/**
* Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.
*
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export {
startSession,
endSession,
captureSession,
withActiveSpan,
addEventProcessor,
} from './exports';
export {
Expand Down Expand Up @@ -93,6 +92,7 @@ export {
getSpanDescendants,
getStatusMessage,
getRootSpan,
getActiveSpan,
} from './utils/spanUtils';
export { applySdkMetadata } from './utils/sdkMetadata';
export { DEFAULT_ENVIRONMENT } from './constants';
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/metrics/aggregator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Client, MeasurementUnit, MetricsAggregator as MetricsAggregatorBase, Primitive } from '@sentry/types';
import { timestampInSeconds } from '@sentry/utils';
import { updateMetricSummaryOnActiveSpan } from '../utils/spanUtils';
import { DEFAULT_FLUSH_INTERVAL, MAX_WEIGHT, NAME_AND_TAG_KEY_NORMALIZATION_REGEX, SET_METRIC_TYPE } from './constants';
import { captureAggregateMetrics } from './envelope';
import { METRIC_MAP } from './instance';
import { updateMetricSummaryOnActiveSpan } from './metric-summary';
import type { MetricBucket, MetricType } from './types';
import { getBucketKey, sanitizeTags } from './utils';

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/metrics/browser-aggregator.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Client, MeasurementUnit, MetricsAggregator, Primitive } from '@sentry/types';
import { timestampInSeconds } from '@sentry/utils';
import { updateMetricSummaryOnActiveSpan } from '../utils/spanUtils';
import { DEFAULT_BROWSER_FLUSH_INTERVAL, NAME_AND_TAG_KEY_NORMALIZATION_REGEX, SET_METRIC_TYPE } from './constants';
import { captureAggregateMetrics } from './envelope';
import { METRIC_MAP } from './instance';
import { updateMetricSummaryOnActiveSpan } from './metric-summary';
import type { MetricBucket, MetricType } from './types';
import { getBucketKey, sanitizeTags } from './utils';

Expand Down
71 changes: 34 additions & 37 deletions packages/core/src/metrics/metric-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { MeasurementUnit, Span } from '@sentry/types';
import type { MetricSummary } from '@sentry/types';
import type { Primitive } from '@sentry/types';
import { dropUndefinedKeys } from '@sentry/utils';
import { getActiveSpan } from '../tracing/utils';
import type { MetricType } from './types';

/**
Expand Down Expand Up @@ -40,52 +39,50 @@ export function getMetricSummaryJsonForSpan(span: Span): Record<string, Array<Me
}

/**
* Updates the metric summary on the currently active span
* Updates the metric summary on a span.
*/
export function updateMetricSummaryOnActiveSpan(
export function updateMetricSummaryOnSpan(
span: Span,
metricType: MetricType,
sanitizedName: string,
value: number,
unit: MeasurementUnit,
tags: Record<string, Primitive>,
bucketKey: string,
): void {
const span = getActiveSpan();
if (span) {
const storage = getMetricStorageForSpan(span) || new Map<string, [string, MetricSummary]>();
const storage = getMetricStorageForSpan(span) || new Map<string, [string, MetricSummary]>();

const exportKey = `${metricType}:${sanitizedName}@${unit}`;
const bucketItem = storage.get(bucketKey);
const exportKey = `${metricType}:${sanitizedName}@${unit}`;
const bucketItem = storage.get(bucketKey);

if (bucketItem) {
const [, summary] = bucketItem;
storage.set(bucketKey, [
exportKey,
{
min: Math.min(summary.min, value),
max: Math.max(summary.max, value),
count: (summary.count += 1),
sum: (summary.sum += value),
tags: summary.tags,
},
]);
} else {
storage.set(bucketKey, [
exportKey,
{
min: value,
max: value,
count: 1,
sum: value,
tags,
},
]);
}

if (!SPAN_METRIC_SUMMARY) {
SPAN_METRIC_SUMMARY = new WeakMap();
}
if (bucketItem) {
const [, summary] = bucketItem;
storage.set(bucketKey, [
exportKey,
{
min: Math.min(summary.min, value),
max: Math.max(summary.max, value),
count: (summary.count += 1),
sum: (summary.sum += value),
tags: summary.tags,
},
]);
} else {
storage.set(bucketKey, [
exportKey,
{
min: value,
max: value,
count: 1,
sum: value,
tags,
},
]);
}

SPAN_METRIC_SUMMARY.set(span, storage);
if (!SPAN_METRIC_SUMMARY) {
SPAN_METRIC_SUMMARY = new WeakMap();
}

SPAN_METRIC_SUMMARY.set(span, storage);
}
3 changes: 1 addition & 2 deletions packages/core/src/tracing/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import {
} from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { getRootSpan } from '../utils/spanUtils';
import { getActiveSpan, getRootSpan } from '../utils/spanUtils';
import { SPAN_STATUS_ERROR } from './spanstatus';
import { getActiveSpan } from './utils';

let errorsInstrumented = false;

Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/tracing/idleSpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ import { getClient, getCurrentScope } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
import { getSpanDescendants, removeChildSpanFromSpan, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';
import {
getActiveSpan,
getSpanDescendants,
removeChildSpanFromSpan,
spanTimeInputToSeconds,
spanToJSON,
} from '../utils/spanUtils';
import { SentryNonRecordingSpan } from './sentryNonRecordingSpan';
import { SPAN_STATUS_ERROR } from './spanstatus';
import { startInactiveSpan } from './trace';
import { getActiveSpan } from './utils';

export const TRACING_DEFAULTS = {
idleTimeout: 1_000,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/tracing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export { SentrySpan } from './sentrySpan';
export { SentryNonRecordingSpan } from './sentryNonRecordingSpan';
export { Transaction } from './transaction';
// eslint-disable-next-line deprecation/deprecation
export { getActiveTransaction, getActiveSpan } from './utils';
export { getActiveTransaction } from './utils';
export {
setHttpStatus,
getSpanStatusFromHttpCode,
Expand All @@ -15,6 +15,7 @@ export {
startInactiveSpan,
startSpanManual,
continueTrace,
withActiveSpan,
} from './trace';
export { getDynamicSamplingContextFromClient, getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';
export { setMeasurement } from './measurement';
4 changes: 1 addition & 3 deletions packages/core/src/tracing/measurement.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { MeasurementUnit, Span, Transaction } from '@sentry/types';
import { getRootSpan } from '../utils/spanUtils';

import { getActiveSpan } from './utils';
import { getActiveSpan, getRootSpan } from '../utils/spanUtils';

/**
* Adds a measurement to the current active transaction.
Expand Down
56 changes: 53 additions & 3 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import type { Hub, Scope, Span, SpanTimeInput, StartSpanOptions, TransactionContext } from '@sentry/types';

import { dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';
import type { AsyncContextStrategy } from '../asyncContext';
import { getMainCarrier } from '../asyncContext';
import { getCurrentScope, getIsolationScope, withScope } from '../currentScopes';

import { DEBUG_BUILD } from '../debug-build';
import { getCurrentHub } from '../hub';
import { getAsyncContextStrategy, getCurrentHub } from '../hub';
import { handleCallbackErrors } from '../utils/handleCallbackErrors';
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
import { addChildSpanToSpan, spanIsSampled, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';
import {
addChildSpanToSpan,
getActiveSpan,
spanIsSampled,
spanTimeInputToSeconds,
spanToJSON,
} from '../utils/spanUtils';
import { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext';
import { SentryNonRecordingSpan } from './sentryNonRecordingSpan';
import type { SentrySpan } from './sentrySpan';
import { SPAN_STATUS_ERROR } from './spanstatus';
import { getActiveSpan, setCapturedScopesOnSpan } from './utils';
import { setCapturedScopesOnSpan } from './utils';

/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
Expand All @@ -26,6 +34,11 @@ import { getActiveSpan, setCapturedScopesOnSpan } from './utils';
* and the `span` returned from the callback will be undefined.
*/
export function startSpan<T>(context: StartSpanOptions, callback: (span: Span) => T): T {
const acs = getAcs();
if (acs.startSpan) {
return acs.startSpan(context, callback);
}

const spanContext = normalizeContext(context);

return withScope(context.scope, scope => {
Expand Down Expand Up @@ -73,6 +86,11 @@ export function startSpan<T>(context: StartSpanOptions, callback: (span: Span) =
* and the `span` returned from the callback will be undefined.
*/
export function startSpanManual<T>(context: StartSpanOptions, callback: (span: Span, finish: () => void) => T): T {
const acs = getAcs();
if (acs.startSpanManual) {
return acs.startSpanManual(context, callback);
}

const spanContext = normalizeContext(context);

return withScope(context.scope, scope => {
Expand Down Expand Up @@ -122,6 +140,11 @@ export function startSpanManual<T>(context: StartSpanOptions, callback: (span: S
* and the `span` returned from the callback will be undefined.
*/
export function startInactiveSpan(context: StartSpanOptions): Span {
const acs = getAcs();
if (acs.startInactiveSpan) {
return acs.startInactiveSpan(context);
}

const spanContext = normalizeContext(context);
// eslint-disable-next-line deprecation/deprecation
const hub = getCurrentHub();
Expand Down Expand Up @@ -248,6 +271,28 @@ export const continueTrace: ContinueTrace = <V>(
});
};

/**
* Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
* passed `null` to start an entirely new span tree.
*
* @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
* spans started within the callback will not be attached to a parent span.
* @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
* @returns the value returned from the provided callback function.
*/
export function withActiveSpan<T>(span: Span | null, callback: (scope: Scope) => T): T {
const acs = getAcs();
if (acs.withActiveSpan) {
return acs.withActiveSpan(span, callback);
}

return withScope(scope => {
// eslint-disable-next-line deprecation/deprecation
scope.setSpan(span || undefined);
return callback(scope);
});
}

function createChildSpanOrTransaction(
hub: Hub,
{
Expand Down Expand Up @@ -340,3 +385,8 @@ function normalizeContext(context: StartSpanOptions): TransactionContext {

return context;
}

function getAcs(): AsyncContextStrategy {
const carrier = getMainCarrier();
return getAsyncContextStrategy(carrier);
}
9 changes: 0 additions & 9 deletions packages/core/src/tracing/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Span, Transaction } from '@sentry/types';
import type { Scope } from '@sentry/types';
import { addNonEnumerableProperty } from '@sentry/utils';
import { getCurrentScope } from '../currentScopes';

import type { Hub } from '../hub';
import { getCurrentHub } from '../hub';
Expand All @@ -23,14 +22,6 @@ export function getActiveTransaction<T extends Transaction>(maybeHub?: Hub): T |
// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils
export { stripUrlQueryAndFragment } from '@sentry/utils';

/**
* Returns the currently active span.
*/
export function getActiveSpan(): Span | undefined {
// eslint-disable-next-line deprecation/deprecation
return getCurrentScope().getSpan();
}

const SCOPE_ON_START_SPAN_FIELD = '_sentryScope';
const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';

Expand Down
Loading