Skip to content

feat(node-experimental): Allow to pass base span options to trace methods #10006

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 2 commits into from
Jan 3, 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
2 changes: 1 addition & 1 deletion packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export const startActiveSpan = startSpan;

/**
* Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span
* after the function is done automatically.
* after the function is done automatically. You'll have to call `span.end()` manually.
*
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
Expand Down
2 changes: 1 addition & 1 deletion packages/node-experimental/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export { getAutoPerformanceIntegrations } from './integrations/getAutoPerformanc
export * as Handlers from './sdk/handlers';
export type { Span } from './types';

export { startSpan, startInactiveSpan, getActiveSpan } from '@sentry/opentelemetry';
export { startSpan, startSpanManual, startInactiveSpan, getActiveSpan } from '@sentry/opentelemetry';
export {
getClient,
addBreadcrumb,
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export {
export { isSentryRequestSpan } from './utils/isSentryRequest';

export { getActiveSpan, getRootSpan } from './utils/getActiveSpan';
export { startSpan, startInactiveSpan } from './trace';
export { startSpan, startSpanManual, startInactiveSpan } from './trace';

export { getCurrentHub, setupGlobalHub, getClient } from './custom/hub';
export { OpenTelemetryScope } from './custom/scope';
Expand Down
44 changes: 42 additions & 2 deletions packages/opentelemetry/src/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function startSpan<T>(spanContext: OpenTelemetrySpanContext, callback: (s

const { name } = spanContext;

return tracer.startActiveSpan(name, span => {
return tracer.startActiveSpan(name, spanContext, span => {
function finishSpan(): void {
span.end();
}
Expand Down Expand Up @@ -57,6 +57,46 @@ export function startSpan<T>(spanContext: OpenTelemetrySpanContext, callback: (s
});
}

/**
* Similar to `Sentry.startSpan`. Wraps a function with a span, but does not finish the span
* after the function is done automatically. You'll have to call `span.end()` manually.
*
* The created span is the active span and will be used as parent by other spans created inside the function
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
*
* Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
*/
export function startSpanManual<T>(spanContext: OpenTelemetrySpanContext, callback: (span: Span) => T): T {
const tracer = getTracer();

const { name } = spanContext;

// @ts-expect-error - isThenable returns the wrong type
return tracer.startActiveSpan(name, spanContext, span => {
_applySentryAttributesToSpan(span, spanContext);

let maybePromiseResult: T;
try {
maybePromiseResult = callback(span);
} catch (e) {
span.setStatus({ code: SpanStatusCode.ERROR });
throw e;
}

if (isThenable(maybePromiseResult)) {
return maybePromiseResult.then(
res => res,
e => {
span.setStatus({ code: SpanStatusCode.ERROR });
throw e;
},
);
}

return maybePromiseResult;
});
}

/**
* @deprecated Use {@link startSpan} instead.
*/
Expand All @@ -77,7 +117,7 @@ export function startInactiveSpan(spanContext: OpenTelemetrySpanContext): Span {

const { name } = spanContext;

const span = tracer.startSpan(name);
const span = tracer.startSpan(name, spanContext);

_applySentryAttributesToSpan(span, spanContext);

Expand Down
7 changes: 6 additions & 1 deletion packages/opentelemetry/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Span as WriteableSpan, Tracer } from '@opentelemetry/api';
import type { Attributes, Span as WriteableSpan, SpanKind, TimeInput, Tracer } from '@opentelemetry/api';
import type { BasicTracerProvider, ReadableSpan, Span } from '@opentelemetry/sdk-trace-base';
import type { SpanOrigin, TransactionMetadata, TransactionSource } from '@sentry/types';

Expand All @@ -13,6 +13,11 @@ export interface OpenTelemetrySpanContext {
metadata?: Partial<TransactionMetadata>;
origin?: SpanOrigin;
source?: TransactionSource;

// Base SpanOptions we support
attributes?: Attributes;
kind?: SpanKind;
startTime?: TimeInput;
}

/**
Expand Down
123 changes: 122 additions & 1 deletion packages/opentelemetry/test/trace.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import type { Span } from '@opentelemetry/api';
import { SpanKind } from '@opentelemetry/api';
import { TraceFlags, context, trace } from '@opentelemetry/api';
import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';
import type { PropagationContext } from '@sentry/types';

import { getCurrentHub } from '../src/custom/hub';
import { InternalSentrySemanticAttributes } from '../src/semanticAttributes';
import { startInactiveSpan, startSpan } from '../src/trace';
import { startInactiveSpan, startSpan, startSpanManual } from '../src/trace';
import type { AbstractSpan } from '../src/types';
import { setPropagationContextOnContext } from '../src/utils/contextData';
import { getActiveSpan, getRootSpan } from '../src/utils/getActiveSpan';
import { getSpanKind } from '../src/utils/getSpanKind';
import { getSpanMetadata } from '../src/utils/spanData';
import { spanHasAttributes, spanHasName } from '../src/utils/spanTypes';
import { cleanupOtel, mockSdkInit } from './helpers/mockSdkInit';
Expand Down Expand Up @@ -231,6 +233,33 @@ describe('trace', () => {
},
);
});

it('allows to pass base SpanOptions', () => {
const date = Date.now() - 1000;

startSpan(
{
name: 'outer',
kind: SpanKind.CLIENT,
attributes: {
test1: 'test 1',
test2: 2,
},

startTime: date,
},
span => {
expect(span).toBeDefined();
expect(getSpanName(span)).toEqual('outer');
expect(getSpanAttributes(span)).toEqual({
[InternalSentrySemanticAttributes.SAMPLE_RATE]: 1,
test1: 'test 1',
test2: 2,
});
expect(getSpanKind(span)).toEqual(SpanKind.CLIENT);
},
);
});
});

describe('startInactiveSpan', () => {
Expand Down Expand Up @@ -297,6 +326,98 @@ describe('trace', () => {

expect(getSpanMetadata(span2)).toEqual({ requestPath: 'test-path' });
});

it('allows to pass base SpanOptions', () => {
const date = Date.now() - 1000;

const span = startInactiveSpan({
name: 'outer',
kind: SpanKind.CLIENT,
attributes: {
test1: 'test 1',
test2: 2,
},
startTime: date,
});

expect(span).toBeDefined();
expect(getSpanName(span)).toEqual('outer');
expect(getSpanAttributes(span)).toEqual({
[InternalSentrySemanticAttributes.SAMPLE_RATE]: 1,
test1: 'test 1',
test2: 2,
});
expect(getSpanKind(span)).toEqual(SpanKind.CLIENT);
});
});

describe('startSpanManual', () => {
it('does not automatically finish the span', () => {
expect(getActiveSpan()).toEqual(undefined);

let _outerSpan: Span | undefined;
let _innerSpan: Span | undefined;

const res = startSpanManual({ name: 'outer' }, outerSpan => {
expect(outerSpan).toBeDefined();
_outerSpan = outerSpan;

expect(getSpanName(outerSpan)).toEqual('outer');
expect(getActiveSpan()).toEqual(outerSpan);

startSpanManual({ name: 'inner' }, innerSpan => {
expect(innerSpan).toBeDefined();
_innerSpan = innerSpan;

expect(getSpanName(innerSpan)).toEqual('inner');
expect(getActiveSpan()).toEqual(innerSpan);
});

expect(getSpanEndTime(_innerSpan!)).toEqual([0, 0]);

_innerSpan!.end();

expect(getSpanEndTime(_innerSpan!)).not.toEqual([0, 0]);

return 'test value';
});

expect(getSpanEndTime(_outerSpan!)).toEqual([0, 0]);

_outerSpan!.end();

expect(getSpanEndTime(_outerSpan!)).not.toEqual([0, 0]);

expect(res).toEqual('test value');

expect(getActiveSpan()).toEqual(undefined);
});

it('allows to pass base SpanOptions', () => {
const date = Date.now() - 1000;

startSpanManual(
{
name: 'outer',
kind: SpanKind.CLIENT,
attributes: {
test1: 'test 1',
test2: 2,
},
startTime: date,
},
span => {
expect(span).toBeDefined();
expect(getSpanName(span)).toEqual('outer');
expect(getSpanAttributes(span)).toEqual({
[InternalSentrySemanticAttributes.SAMPLE_RATE]: 1,
test1: 'test 1',
test2: 2,
});
expect(getSpanKind(span)).toEqual(SpanKind.CLIENT);
},
);
});
});
});

Expand Down