|
| 1 | +import type { Context, Span, SpanOptions, Tracer, TracerProvider } from '@opentelemetry/api'; |
| 2 | +import { trace } from '@opentelemetry/api'; |
| 3 | +import { startInactiveSpan, startSpan } from '@sentry/core'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Set up a mock OTEL tracer to allow inter-op with OpenTelemetry emitted spans. |
| 7 | + * This is not perfect but handles easy/common use cases. |
| 8 | + */ |
| 9 | +export function setupOpenTelemetryTracer(): void { |
| 10 | + trace.setGlobalTracerProvider(new SentryCloudflareTraceProvider()); |
| 11 | +} |
| 12 | + |
| 13 | +class SentryCloudflareTraceProvider implements TracerProvider { |
| 14 | + private readonly _tracers: Map<string, Tracer> = new Map(); |
| 15 | + |
| 16 | + public getTracer(name: string, version?: string, options?: { schemaUrl?: string }): Tracer { |
| 17 | + const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`; |
| 18 | + if (!this._tracers.has(key)) { |
| 19 | + this._tracers.set(key, new SentryCloudflareTracer()); |
| 20 | + } |
| 21 | + |
| 22 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 23 | + return this._tracers.get(key)!; |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +class SentryCloudflareTracer implements Tracer { |
| 28 | + public startSpan(name: string, options?: SpanOptions): Span { |
| 29 | + return startInactiveSpan({ name, ...options }); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * NOTE: This does not handle `context` being passed in. It will always put spans on the current scope. |
| 34 | + */ |
| 35 | + public startActiveSpan<F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>; |
| 36 | + public startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, fn: F): ReturnType<F>; |
| 37 | + public startActiveSpan<F extends (span: Span) => unknown>( |
| 38 | + name: string, |
| 39 | + options: SpanOptions, |
| 40 | + context: Context, |
| 41 | + fn: F, |
| 42 | + ): ReturnType<F>; |
| 43 | + public startActiveSpan<F extends (span: Span) => unknown>( |
| 44 | + name: string, |
| 45 | + options: unknown, |
| 46 | + context?: unknown, |
| 47 | + fn?: F, |
| 48 | + ): ReturnType<F> { |
| 49 | + const opts = typeof options === 'object' && options !== null ? options : {}; |
| 50 | + |
| 51 | + const spanOpts = { |
| 52 | + name, |
| 53 | + ...opts, |
| 54 | + }; |
| 55 | + |
| 56 | + const callback = ( |
| 57 | + typeof options === 'function' |
| 58 | + ? options |
| 59 | + : typeof context === 'function' |
| 60 | + ? context |
| 61 | + : typeof fn === 'function' |
| 62 | + ? fn |
| 63 | + : // eslint-disable-next-line @typescript-eslint/no-empty-function |
| 64 | + () => {} |
| 65 | + ) as F; |
| 66 | + |
| 67 | + return startSpan(spanOpts, callback) as ReturnType<F>; |
| 68 | + } |
| 69 | +} |
0 commit comments