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(otel): Add basic SentrySpanProcessor #6023
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 |
---|---|---|
@@ -1,6 +1,3 @@ | ||
/** | ||
* Test function | ||
*/ | ||
export function test(): void { | ||
// no-op | ||
} | ||
import '@sentry/tracing'; | ||
|
||
export { SentrySpanProcessor } from './spanprocessor'; |
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,115 @@ | ||
import { Context } from '@opentelemetry/api'; | ||
import { Span as OtelSpan, SpanProcessor as OtelSpanProcessor } from '@opentelemetry/sdk-trace-base'; | ||
import { getCurrentHub } from '@sentry/core'; | ||
import { Span as SentrySpan, TransactionContext } from '@sentry/types'; | ||
import { logger } from '@sentry/utils'; | ||
|
||
/** | ||
* Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via | ||
* the Sentry SDK. | ||
*/ | ||
export class SentrySpanProcessor implements OtelSpanProcessor { | ||
// public only for testing | ||
public readonly _map: Map<SentrySpan['spanId'], SentrySpan> = new Map<SentrySpan['spanId'], SentrySpan>(); | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public onStart(otelSpan: OtelSpan, _parentContext: Context): void { | ||
const hub = getCurrentHub(); | ||
if (!hub) { | ||
__DEBUG_BUILD__ && logger.error('SentrySpanProcessor has triggered onStart before a hub has been setup.'); | ||
return; | ||
} | ||
const scope = hub.getScope(); | ||
if (!scope) { | ||
__DEBUG_BUILD__ && logger.error('SentrySpanProcessor has triggered onStart before a scope has been setup.'); | ||
return; | ||
} | ||
|
||
// TODO: handle sentry requests | ||
// if isSentryRequest(otelSpan) return; | ||
|
||
const otelSpanId = otelSpan.spanContext().spanId; | ||
const otelParentSpanId = otelSpan.parentSpanId; | ||
|
||
// Otel supports having multiple non-nested spans at the same time | ||
// so we cannot use hub.getSpan(), as we cannot rely on this being on the current span | ||
const sentryParentSpan = otelParentSpanId && this._map.get(otelParentSpanId); | ||
|
||
if (sentryParentSpan) { | ||
const sentryChildSpan = sentryParentSpan.startChild({ | ||
description: otelSpan.name, | ||
// instrumentor: 'otel', | ||
startTimestamp: otelSpan.startTime[0], | ||
spanId: otelSpanId, | ||
}); | ||
|
||
this._map.set(otelSpanId, sentryChildSpan); | ||
} else { | ||
const traceCtx = getTraceData(otelSpan); | ||
const transaction = hub.startTransaction({ | ||
name: otelSpan.name, | ||
...traceCtx, | ||
// instrumentor: 'otel', | ||
startTimestamp: otelSpan.startTime[0], | ||
spanId: otelSpanId, | ||
}); | ||
|
||
this._map.set(otelSpanId, transaction); | ||
} | ||
} | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public onEnd(otelSpan: OtelSpan): void { | ||
const otelSpanId = otelSpan.spanContext().spanId; | ||
const mapVal = this._map.get(otelSpanId); | ||
|
||
if (!mapVal) { | ||
__DEBUG_BUILD__ && | ||
logger.error(`SentrySpanProcessor could not find span with OTEL-spanId ${otelSpanId} to finish.`); | ||
return; | ||
} | ||
|
||
const sentrySpan = mapVal; | ||
|
||
// TODO: actually add context etc. to span | ||
// updateSpanWithOtelData(sentrySpan, otelSpan); | ||
|
||
sentrySpan.finish(otelSpan.endTime[0]); | ||
|
||
this._map.delete(otelSpanId); | ||
} | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public shutdown(): Promise<void> { | ||
return Promise.resolve(); | ||
} | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public async forceFlush(): Promise<void> { | ||
const client = getCurrentHub().getClient(); | ||
if (client) { | ||
return client.flush().then(); | ||
} | ||
return Promise.resolve(); | ||
} | ||
} | ||
|
||
function getTraceData(otelSpan: OtelSpan): Partial<TransactionContext> { | ||
const spanContext = otelSpan.spanContext(); | ||
const traceId = spanContext.traceId; | ||
const spanId = spanContext.spanId; | ||
|
||
const parentSpanId = otelSpan.parentSpanId; | ||
return { spanId, traceId, parentSpanId }; | ||
} | ||
|
||
// function updateSpanWithOtelData(sentrySpan: SentrySpan, otelSpan: OtelSpan): void { | ||
// } |
This file was deleted.
Oops, something went wrong.
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,141 @@ | ||
import * as OpenTelemetry from '@opentelemetry/api'; | ||
import { Span as OtelSpan } from '@opentelemetry/sdk-trace-base'; | ||
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; | ||
import { Hub, makeMain } from '@sentry/core'; | ||
import { addExtensionMethods, Span as SentrySpan, Transaction } from '@sentry/tracing'; | ||
|
||
import { SentrySpanProcessor } from '../src/spanprocessor'; | ||
|
||
// Integration Test of SentrySpanProcessor | ||
|
||
beforeAll(() => { | ||
addExtensionMethods(); | ||
}); | ||
|
||
describe('SentrySpanProcessor', () => { | ||
let hub: Hub; | ||
let provider: NodeTracerProvider; | ||
let spanProcessor: SentrySpanProcessor; | ||
|
||
beforeEach(() => { | ||
hub = new Hub(); | ||
makeMain(hub); | ||
|
||
spanProcessor = new SentrySpanProcessor(); | ||
provider = new NodeTracerProvider(); | ||
provider.addSpanProcessor(spanProcessor); | ||
provider.register(); | ||
}); | ||
|
||
afterEach(async () => { | ||
await provider.forceFlush(); | ||
await provider.shutdown(); | ||
}); | ||
|
||
function getSpanForOtelSpan(otelSpan: OtelSpan | OpenTelemetry.Span) { | ||
return spanProcessor._map.get(otelSpan.spanContext().spanId); | ||
} | ||
|
||
it('creates a transaction', async () => { | ||
const startTime = otelNumberToHrtime(new Date().valueOf()); | ||
|
||
const otelSpan = provider.getTracer('default').startSpan('GET /users', { startTime }) as OtelSpan; | ||
|
||
const sentrySpanTransaction = getSpanForOtelSpan(otelSpan) as Transaction | undefined; | ||
expect(sentrySpanTransaction).toBeInstanceOf(Transaction); | ||
|
||
expect(sentrySpanTransaction?.name).toBe('GET /users'); | ||
expect(sentrySpanTransaction?.startTimestamp).toEqual(otelSpan.startTime[0]); | ||
expect(sentrySpanTransaction?.startTimestamp).toEqual(startTime[0]); | ||
expect(sentrySpanTransaction?.traceId).toEqual(otelSpan.spanContext().traceId); | ||
expect(sentrySpanTransaction?.parentSpanId).toEqual(otelSpan.parentSpanId); | ||
expect(sentrySpanTransaction?.spanId).toEqual(otelSpan.spanContext().spanId); | ||
|
||
expect(hub.getScope()?.getSpan()).toBeUndefined(); | ||
|
||
const endTime = otelNumberToHrtime(new Date().valueOf()); | ||
otelSpan.end(endTime); | ||
|
||
expect(sentrySpanTransaction?.endTimestamp).toBe(endTime[0]); | ||
expect(sentrySpanTransaction?.endTimestamp).toBe(otelSpan.endTime[0]); | ||
|
||
expect(hub.getScope()?.getSpan()).toBeUndefined(); | ||
}); | ||
|
||
it('creates a child span if there is a running transaction', () => { | ||
const tracer = provider.getTracer('default'); | ||
|
||
tracer.startActiveSpan('GET /users', parentOtelSpan => { | ||
tracer.startActiveSpan('SELECT * FROM users;', child => { | ||
const childOtelSpan = child as OtelSpan; | ||
|
||
const sentrySpanTransaction = getSpanForOtelSpan(parentOtelSpan) as Transaction | undefined; | ||
expect(sentrySpanTransaction).toBeInstanceOf(Transaction); | ||
|
||
const sentrySpan = getSpanForOtelSpan(childOtelSpan); | ||
expect(sentrySpan).toBeInstanceOf(SentrySpan); | ||
expect(sentrySpan?.description).toBe('SELECT * FROM users;'); | ||
expect(sentrySpan?.startTimestamp).toEqual(childOtelSpan.startTime[0]); | ||
expect(sentrySpan?.spanId).toEqual(childOtelSpan.spanContext().spanId); | ||
expect(sentrySpan?.parentSpanId).toEqual(sentrySpanTransaction?.spanId); | ||
|
||
expect(hub.getScope()?.getSpan()).toBeUndefined(); | ||
|
||
const endTime = otelNumberToHrtime(new Date().valueOf()); | ||
child.end(endTime); | ||
|
||
expect(sentrySpan?.endTimestamp).toEqual(childOtelSpan.endTime[0]); | ||
expect(sentrySpan?.endTimestamp).toEqual(endTime[0]); | ||
}); | ||
|
||
parentOtelSpan.end(); | ||
}); | ||
}); | ||
|
||
it('allows to create multiple child spans on same level', () => { | ||
const tracer = provider.getTracer('default'); | ||
|
||
tracer.startActiveSpan('GET /users', parentOtelSpan => { | ||
const sentrySpanTransaction = getSpanForOtelSpan(parentOtelSpan) as Transaction | undefined; | ||
|
||
expect(sentrySpanTransaction).toBeInstanceOf(SentrySpan); | ||
expect(sentrySpanTransaction?.name).toBe('GET /users'); | ||
|
||
// Create some parallel, independent spans | ||
const span1 = tracer.startSpan('SELECT * FROM users;') as OtelSpan; | ||
const span2 = tracer.startSpan('SELECT * FROM companies;') as OtelSpan; | ||
const span3 = tracer.startSpan('SELECT * FROM locations;') as OtelSpan; | ||
|
||
const sentrySpan1 = getSpanForOtelSpan(span1); | ||
const sentrySpan2 = getSpanForOtelSpan(span2); | ||
const sentrySpan3 = getSpanForOtelSpan(span3); | ||
|
||
expect(sentrySpan1?.parentSpanId).toEqual(sentrySpanTransaction?.spanId); | ||
expect(sentrySpan2?.parentSpanId).toEqual(sentrySpanTransaction?.spanId); | ||
expect(sentrySpan3?.parentSpanId).toEqual(sentrySpanTransaction?.spanId); | ||
|
||
expect(sentrySpan1?.description).toEqual('SELECT * FROM users;'); | ||
expect(sentrySpan2?.description).toEqual('SELECT * FROM companies;'); | ||
expect(sentrySpan3?.description).toEqual('SELECT * FROM locations;'); | ||
|
||
span1.end(); | ||
span2.end(); | ||
span3.end(); | ||
|
||
parentOtelSpan.end(); | ||
}); | ||
}); | ||
}); | ||
|
||
// OTEL expects a custom date format | ||
const NANOSECOND_DIGITS = 9; | ||
const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); | ||
|
||
function otelNumberToHrtime(epochMillis: number): OpenTelemetry.HrTime { | ||
const epochSeconds = epochMillis / 1000; | ||
// Decimals only. | ||
const seconds = Math.trunc(epochSeconds); | ||
// Round sub-nanosecond accuracy to nanosecond. | ||
const nanos = Number((epochSeconds - seconds).toFixed(NANOSECOND_DIGITS)) * SECOND_TO_NANOSECONDS; | ||
return [seconds, nanos]; | ||
} |
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 |
---|---|---|
|
@@ -132,9 +132,7 @@ export interface Span extends SpanContext { | |
* Creates a new `Span` while setting the current `Span.id` as `parentSpanId`. | ||
* Also the `sampled` decision will be inherited. | ||
*/ | ||
startChild( | ||
spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceId' | 'parentSpanId'>>, | ||
): Span; | ||
startChild(spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'sampled' | 'traceId' | 'parentSpanId'>>): Span; | ||
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. I think this was missed in #6028? 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. yes 🤦 |
||
|
||
/** | ||
* Determines whether span was successful (HTTP200) | ||
|
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
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.
It's not super nice to make this public just so we can use it in tests, so if there are other ideas for this, let me know. It works, at least 😅
Also FYI I changed this to a
Map
instead of{}
, as that makesdelete()
nicer imho. I think there shouldn't really be a perf difference, but let me know if we should rather leave this a POJO.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.
Using a map seems fine to me - cleaner pattern overall.