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

feat(core): Add trace function #7556

Merged
merged 1 commit into from
Mar 22, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/tracing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { extractTraceparentData, getActiveTransaction, stripUrlQueryAndFragment,
// eslint-disable-next-line deprecation/deprecation
export { SpanStatus } from './spanstatus';
export type { SpanStatusType } from './span';
export { trace } from './trace';
65 changes: 65 additions & 0 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { TransactionContext } from '@sentry/types';
import { isThenable } from '@sentry/utils';

import { getCurrentHub } from '../hub';
import type { Span } from './span';

/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
*
* This function is meant to be used internally and may break at any time. Use at your own risk.
*
* @internal
* @private
*/
export function trace<T>(
context: TransactionContext,
callback: (span: Span) => T,
Copy link
Member

Choose a reason for hiding this comment

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

super-l: WDYT about renaming callback to something like traceTarget / traceSubject or something along these lines? The way I understand this function, we want to start a txn or a span for this callback so I'd say we should give it a good name. callback sounds a little generic to me.
But ofc we can (and probably will) iterate on this function in the future, so really, feel free to disregard this comment.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm going to use callback for now since this is the language we are using for the cross SDK discussions about this, but you do make a good point. I'll come back and re-visit this after we chat about it as a group.

// eslint-disable-next-line @typescript-eslint/no-empty-function
onError: (error: unknown) => void = () => {},
): T {
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 hub = getCurrentHub();
const scope = hub.getScope();

const parentSpan = scope.getSpan();
const activeSpan = parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);
scope.setSpan(activeSpan);

function finishAndSetSpan(): void {
activeSpan.finish();
hub.getScope().setSpan(parentSpan);
}

let maybePromiseResult: T;
try {
maybePromiseResult = callback(activeSpan);
} catch (e) {
activeSpan.setStatus('internal_error');
onError(e);
finishAndSetSpan();
throw e;
}

if (isThenable(maybePromiseResult)) {
Promise.resolve(maybePromiseResult).then(
() => {
finishAndSetSpan();
},
e => {
activeSpan.setStatus('internal_error');
onError(e);
finishAndSetSpan();
},
);
} else {
finishAndSetSpan();
}

return maybePromiseResult;
}
170 changes: 170 additions & 0 deletions packages/core/test/lib/tracing/trace.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { addTracingExtensions, Hub, makeMain } from '../../../src';
import { trace } from '../../../src/tracing';
import { getDefaultTestClientOptions, TestClient } from '../../mocks/client';

beforeAll(() => {
addTracingExtensions();
});

const enum Type {
Sync = 'sync',
Async = 'async',
}

let hub: Hub;
let client: TestClient;

describe('trace', () => {
beforeEach(() => {
const options = getDefaultTestClientOptions({ tracesSampleRate: 0.0 });
client = new TestClient(options);
hub = new Hub(client);
makeMain(hub);
});

describe.each([
// isSync, isError, callback, expectedReturnValue
[Type.Async, false, () => Promise.resolve('async good'), 'async good'],
[Type.Sync, false, () => 'sync good', 'sync good'],
[Type.Async, true, () => Promise.reject('async bad'), 'async bad'],
[
Type.Sync,
true,
() => {
throw 'sync bad';
},
'sync bad',
],
])('with %s callback and error %s', (_type, isError, callback, expected) => {
it('should return the same value as the callback', async () => {
try {
const result = await trace({ name: 'GET users/[id]' }, () => {
return callback();
});
expect(result).toEqual(expected);
} catch (e) {
expect(e).toEqual(expected);
}
});

it('creates a transaction', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
Copy link
Member

Choose a reason for hiding this comment

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

Making good use of hooks - I love it 😄

ref = transaction;
});
try {
await trace({ name: 'GET users/[id]' }, () => {
return callback();
});
} catch (e) {
//
}
expect(ref).toBeDefined();

expect(ref.name).toEqual('GET users/[id]');
expect(ref.status).toEqual(isError ? 'internal_error' : undefined);
});

it('allows traceparent information to be overriden', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
ref = transaction;
});
try {
await trace(
{
name: 'GET users/[id]',
parentSampled: true,
traceId: '12345678901234567890123456789012',
parentSpanId: '1234567890123456',
},
() => {
return callback();
},
);
} catch (e) {
//
}
expect(ref).toBeDefined();

expect(ref.sampled).toEqual(true);
expect(ref.traceId).toEqual('12345678901234567890123456789012');
expect(ref.parentSpanId).toEqual('1234567890123456');
});

it('allows for transaction to be mutated', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
ref = transaction;
});
try {
await trace({ name: 'GET users/[id]' }, span => {
span.op = 'http.server';
return callback();
});
} catch (e) {
//
}

expect(ref.op).toEqual('http.server');
});

it('creates a span with correct description', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
ref = transaction;
});
try {
await trace({ name: 'GET users/[id]', parentSampled: true }, () => {
return trace({ name: 'SELECT * from users' }, () => {
return callback();
});
});
} catch (e) {
//
}

expect(ref.spanRecorder.spans).toHaveLength(2);
expect(ref.spanRecorder.spans[1].description).toEqual('SELECT * from users');
expect(ref.spanRecorder.spans[1].parentSpanId).toEqual(ref.spanId);
expect(ref.spanRecorder.spans[1].status).toEqual(isError ? 'internal_error' : undefined);
});

it('allows for span to be mutated', async () => {
let ref: any = undefined;
client.on('finishTransaction', transaction => {
ref = transaction;
});
try {
await trace({ name: 'GET users/[id]', parentSampled: true }, () => {
return trace({ name: 'SELECT * from users' }, childSpan => {
childSpan.op = 'db.query';
return callback();
});
});
} catch (e) {
//
}

expect(ref.spanRecorder.spans).toHaveLength(2);
expect(ref.spanRecorder.spans[1].op).toEqual('db.query');
});

it('calls `onError` hook', async () => {
const onError = jest.fn();
try {
await trace(
{ name: 'GET users/[id]' },
() => {
return callback();
},
onError,
);
} catch (e) {
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(e);
}
expect(onError).toHaveBeenCalledTimes(isError ? 1 : 0);
});
});
});