-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
// 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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
}); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 liketraceTarget
/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.
There was a problem hiding this comment.
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.