Skip to content

feat(core): Allow to pass start/end timestamp for spans flexibly #10060

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 4 commits into from
Jan 5, 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
10 changes: 5 additions & 5 deletions packages/core/src/tracing/idletransaction.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
/* eslint-disable max-lines */
import type { TransactionContext } from '@sentry/types';
import type { SpanTimeInput, TransactionContext } from '@sentry/types';
import { logger, timestampInSeconds } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import type { Hub } from '../hub';
import { spanTimeInputToSeconds } from '../utils/spanUtils';
import type { Span } from './span';
import { SpanRecorder } from './span';
import { Transaction } from './transaction';
import { ensureTimestampInSeconds } from './utils';

export const TRACING_DEFAULTS = {
idleTimeout: 1000,
Expand Down Expand Up @@ -138,8 +138,8 @@ export class IdleTransaction extends Transaction {
}

/** {@inheritDoc} */
public end(endTimestamp: number = timestampInSeconds()): string | undefined {
const endTimestampInS = ensureTimestampInSeconds(endTimestamp);
public end(endTimestamp?: SpanTimeInput): string | undefined {
const endTimestampInS = spanTimeInputToSeconds(endTimestamp);

this._finished = true;
this.activities = {};
Expand All @@ -153,7 +153,7 @@ export class IdleTransaction extends Transaction {
logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);

for (const callback of this._beforeFinishCallbacks) {
callback(this, endTimestamp);
callback(this, endTimestampInS);
}

this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {
Expand Down
9 changes: 4 additions & 5 deletions packages/core/src/tracing/span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import type {
SpanAttributes,
SpanContext,
SpanOrigin,
SpanTimeInput,
TraceContext,
Transaction,
} from '@sentry/types';
import { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import { spanToTraceContext, spanToTraceHeader } from '../utils/spanUtils';
import { ensureTimestampInSeconds } from './utils';
import { spanTimeInputToSeconds, spanToTraceContext, spanToTraceHeader } from '../utils/spanUtils';

/**
* Keeps track of finished spans for a given transaction
Expand Down Expand Up @@ -300,7 +300,7 @@ export class Span implements SpanInterface {
}

/** @inheritdoc */
public end(endTimestamp?: number): void {
public end(endTimestamp?: SpanTimeInput): void {
if (
DEBUG_BUILD &&
// Don't call this for transactions
Expand All @@ -313,8 +313,7 @@ export class Span implements SpanInterface {
}
}

this.endTimestamp =
typeof endTimestamp === 'number' ? ensureTimestampInSeconds(endTimestamp) : timestampInSeconds();
this.endTimestamp = spanTimeInputToSeconds(endTimestamp);
}

/**
Expand Down
35 changes: 24 additions & 11 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Span, TransactionContext } from '@sentry/types';
import type { Span, SpanTimeInput, TransactionContext } from '@sentry/types';
import { dropUndefinedKeys, logger, tracingContextFromHeaders } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
Expand All @@ -7,6 +7,12 @@ import type { Hub } from '../hub';
import { getCurrentHub } from '../hub';
import { handleCallbackErrors } from '../utils/handleCallbackErrors';
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
import { spanTimeInputToSeconds } from '../utils/spanUtils';

interface StartSpanOptions extends TransactionContext {
/** A manually specified start time for the created `Span` object. */
startTime?: SpanTimeInput;
}

/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
Expand Down Expand Up @@ -65,7 +71,7 @@ export function trace<T>(
* or you didn't set `tracesSampleRate`, this function will not generate spans
* and the `span` returned from the callback will be undefined.
*/
export function startSpan<T>(context: TransactionContext, callback: (span: Span | undefined) => T): T {
export function startSpan<T>(context: StartSpanOptions, callback: (span: Span | undefined) => T): T {
const ctx = normalizeContext(context);

return withScope(scope => {
Expand Down Expand Up @@ -105,7 +111,7 @@ export const startActiveSpan = startSpan;
* and the `span` returned from the callback will be undefined.
*/
export function startSpanManual<T>(
context: TransactionContext,
context: StartSpanOptions,
callback: (span: Span | undefined, finish: () => void) => T,
): T {
const ctx = normalizeContext(context);
Expand Down Expand Up @@ -143,17 +149,12 @@ export function startSpanManual<T>(
* or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
* and the `span` returned from the callback will be undefined.
*/
export function startInactiveSpan(context: TransactionContext): Span | undefined {
export function startInactiveSpan(context: StartSpanOptions): Span | undefined {
if (!hasTracingEnabled()) {
return undefined;
}

const ctx = { ...context };
// If a name is set and a description is not, set the description to the name.
if (ctx.name !== undefined && ctx.description === undefined) {
ctx.description = ctx.name;
}

const ctx = normalizeContext(context);
const hub = getCurrentHub();
const parentSpan = getActiveSpan();
return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);
Expand Down Expand Up @@ -238,12 +239,24 @@ function createChildSpanOrTransaction(
return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);
}

function normalizeContext(context: TransactionContext): TransactionContext {
/**
* This converts StartSpanOptions to TransactionContext.
* For the most part (for now) we accept the same options,
* but some of them need to be transformed.
*
* Eventually the StartSpanOptions will be more aligned with OpenTelemetry.
*/
function normalizeContext(context: StartSpanOptions): TransactionContext {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a small comment explaining what is normalized and why things need normalization?

const ctx = { ...context };
// If a name is set and a description is not, set the description to the name.
if (ctx.name !== undefined && ctx.description === undefined) {
ctx.description = ctx.name;
}

if (context.startTime) {
ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);
delete ctx.startTime;
}

return ctx;
}
11 changes: 5 additions & 6 deletions packages/core/src/tracing/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ import type {
DynamicSamplingContext,
MeasurementUnit,
Measurements,
SpanTimeInput,
Transaction as TransactionInterface,
TransactionContext,
TransactionEvent,
TransactionMetadata,
} from '@sentry/types';
import { dropUndefinedKeys, logger, timestampInSeconds } from '@sentry/utils';
import { dropUndefinedKeys, logger } from '@sentry/utils';

import { DEBUG_BUILD } from '../debug-build';
import type { Hub } from '../hub';
import { getCurrentHub } from '../hub';
import { spanToTraceContext } from '../utils/spanUtils';
import { spanTimeInputToSeconds, spanToTraceContext } from '../utils/spanUtils';
import { getDynamicSamplingContextFromClient } from './dynamicSamplingContext';
import { Span as SpanClass, SpanRecorder } from './span';
import { ensureTimestampInSeconds } from './utils';

/** JSDoc */
export class Transaction extends SpanClass implements TransactionInterface {
Expand Down Expand Up @@ -147,9 +147,8 @@ export class Transaction extends SpanClass implements TransactionInterface {
/**
* @inheritDoc
*/
public end(endTimestamp?: number): string | undefined {
const timestampInS =
typeof endTimestamp === 'number' ? ensureTimestampInSeconds(endTimestamp) : timestampInSeconds();
public end(endTimestamp?: SpanTimeInput): string | undefined {
const timestampInS = spanTimeInputToSeconds(endTimestamp);
const transaction = this._finishTransaction(timestampInS);
if (!transaction) {
return undefined;
Expand Down
8 changes: 0 additions & 8 deletions packages/core/src/tracing/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,3 @@ export { stripUrlQueryAndFragment } from '@sentry/utils';
* @deprecated Import this function from `@sentry/utils` instead
*/
export const extractTraceparentData = _extractTraceparentData;

/**
* Converts a timestamp to second, if it was in milliseconds, or keeps it as second.
*/
export function ensureTimestampInSeconds(timestamp: number): number {
const isMs = timestamp > 9999999999;
return isMs ? timestamp / 1000 : timestamp;
}
32 changes: 30 additions & 2 deletions packages/core/src/utils/spanUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Span, TraceContext } from '@sentry/types';
import { dropUndefinedKeys, generateSentryTraceHeader } from '@sentry/utils';
import type { Span, SpanTimeInput, TraceContext } from '@sentry/types';
import { dropUndefinedKeys, generateSentryTraceHeader, timestampInSeconds } from '@sentry/utils';

/**
* Convert a span to a trace context, which can be sent as the `trace` context in an event.
Expand All @@ -26,3 +26,31 @@ export function spanToTraceContext(span: Span): TraceContext {
export function spanToTraceHeader(span: Span): string {
return generateSentryTraceHeader(span.traceId, span.spanId, span.sampled);
}

/**
* Convert a span time input intp a timestamp in seconds.
*/
export function spanTimeInputToSeconds(input: SpanTimeInput | undefined): number {
if (typeof input === 'number') {
return ensureTimestampInSeconds(input);
}

if (Array.isArray(input)) {
// See {@link HrTime} for the array-based time format
return input[0] + input[1] / 1e9;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is vendored we need to add license

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is only inspired, not copied - only the comment I took verbatim 🤔 but we can also move this to it's own file, then we can still add the licence even if it is adapted from there?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with these kind of things, better be safe than sorry - let's move to it's own file.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!

}

if (input instanceof Date) {
return ensureTimestampInSeconds(input.getTime());
}

return timestampInSeconds();
}

/**
* Converts a timestamp to second, if it was in milliseconds, or keeps it as second.
*/
function ensureTimestampInSeconds(timestamp: number): number {
const isMs = timestamp > 9999999999;
return isMs ? timestamp / 1000 : timestamp;
}
35 changes: 35 additions & 0 deletions packages/core/test/lib/tracing/span.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { timestampInSeconds } from '@sentry/utils';
import { Span } from '../../../src';

describe('span', () => {
Expand Down Expand Up @@ -174,6 +175,40 @@ describe('span', () => {
});
});

describe('end', () => {
it('works without endTimestamp', () => {
const span = new Span();
const now = timestampInSeconds();
span.end();

expect(span.endTimestamp).toBeGreaterThanOrEqual(now);
});

it('works with endTimestamp in seconds', () => {
const span = new Span();
const timestamp = timestampInSeconds() - 1;
span.end(timestamp);

expect(span.endTimestamp).toEqual(timestamp);
});

it('works with endTimestamp in milliseconds', () => {
const span = new Span();
const timestamp = Date.now() - 1000;
span.end(timestamp);

expect(span.endTimestamp).toEqual(timestamp / 1000);
});

it('works with endTimestamp in array form', () => {
const span = new Span();
const seconds = Math.floor(timestampInSeconds() - 1);
span.end([seconds, 0]);

expect(span.endTimestamp).toEqual(seconds);
});
});

// Ensure that attributes & data are merged together
describe('_getData', () => {
it('works without data & attributes', () => {
Expand Down
22 changes: 22 additions & 0 deletions packages/core/test/lib/tracing/trace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,14 @@ describe('startSpan', () => {
expect(ref.spanRecorder.spans[1].status).toEqual(isError ? 'internal_error' : undefined);
});

it('allows to pass a `startTime`', () => {
const start = startSpan({ name: 'outer', startTime: [1234, 0] }, span => {
return span?.startTimestamp;
});

expect(start).toEqual(1234);
});

it('allows for span to be mutated', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
Expand Down Expand Up @@ -222,6 +230,15 @@ describe('startSpanManual', () => {
expect(getCurrentScope()).toBe(initialScope);
expect(initialScope.getSpan()).toBe(undefined);
});

it('allows to pass a `startTime`', () => {
const start = startSpanManual({ name: 'outer', startTime: [1234, 0] }, span => {
span?.end();
return span?.startTimestamp;
});

expect(start).toEqual(1234);
});
});

describe('startInactiveSpan', () => {
Expand All @@ -248,6 +265,11 @@ describe('startInactiveSpan', () => {

expect(initialScope.getSpan()).toBeUndefined();
});

it('allows to pass a `startTime`', () => {
const span = startInactiveSpan({ name: 'outer', startTime: [1234, 0] });
expect(span?.startTimestamp).toEqual(1234);
});
});

describe('continueTrace', () => {
Expand Down
37 changes: 36 additions & 1 deletion packages/core/test/lib/utils/spanUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { TRACEPARENT_REGEXP } from '@sentry/utils';
import { TRACEPARENT_REGEXP, timestampInSeconds } from '@sentry/utils';
import { Span, spanToTraceHeader } from '../../../src';
import { spanTimeInputToSeconds } from '../../../src/utils/spanUtils';

describe('spanToTraceHeader', () => {
test('simple', () => {
Expand All @@ -11,3 +12,37 @@ describe('spanToTraceHeader', () => {
expect(spanToTraceHeader(span)).toMatch(TRACEPARENT_REGEXP);
});
});

describe('spanTimeInputToSeconds', () => {
it('works with undefined', () => {
const now = timestampInSeconds();
expect(spanTimeInputToSeconds(undefined)).toBeGreaterThanOrEqual(now);
});

it('works with a timestamp in seconds', () => {
const timestamp = timestampInSeconds();
expect(spanTimeInputToSeconds(timestamp)).toEqual(timestamp);
});

it('works with a timestamp in milliseconds', () => {
const timestamp = Date.now();
expect(spanTimeInputToSeconds(timestamp)).toEqual(timestamp / 1000);
});

it('works with a Date object', () => {
const timestamp = new Date();
expect(spanTimeInputToSeconds(timestamp)).toEqual(timestamp.getTime() / 1000);
});

it('works with a simple array', () => {
const seconds = Math.floor(timestampInSeconds());
const timestamp: [number, number] = [seconds, 0];
expect(spanTimeInputToSeconds(timestamp)).toEqual(seconds);
});

it('works with a array with nanoseconds', () => {
const seconds = Math.floor(timestampInSeconds());
const timestamp: [number, number] = [seconds, 9000];
expect(spanTimeInputToSeconds(timestamp)).toEqual(seconds + 0.000009);
});
});
2 changes: 1 addition & 1 deletion packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export type {

// eslint-disable-next-line deprecation/deprecation
export type { Severity, SeverityLevel } from './severity';
export type { Span, SpanContext, SpanOrigin, SpanAttributeValue, SpanAttributes } from './span';
export type { Span, SpanContext, SpanOrigin, SpanAttributeValue, SpanAttributes, SpanTimeInput } from './span';
export type { StackFrame } from './stackframe';
export type { Stacktrace, StackParser, StackLineParser, StackLineParserFn } from './stacktrace';
export type { TextEncoderInternal } from './textencoder';
Expand Down
Loading