Skip to content

feat(cloudflare): Allow interop with OpenTelemetry emitted spans #16714

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 3 commits into from
Jun 25, 2025
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
3 changes: 2 additions & 1 deletion packages/cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"access": "public"
},
"dependencies": {
"@sentry/core": "9.31.0"
"@sentry/core": "9.31.0",
"@opentelemetry/api": "^1.9.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.x"
Expand Down
13 changes: 13 additions & 0 deletions packages/cloudflare/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ interface BaseCloudflareOptions {
* @default true
*/
enableDedupe?: boolean;

/**
* The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility
* via a custom trace provider.
* This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.
* HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.
* This should be good enough for many, but not all integrations.
*
* If you want to opt-out of setting up the OpenTelemetry compatibility tracer, set this to `true`.
*
* @default false
*/
skipOpenTelemetrySetup?: boolean;
}

/**
Expand Down
81 changes: 81 additions & 0 deletions packages/cloudflare/src/opentelemetry/tracer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { Context, Span, SpanOptions, Tracer, TracerProvider } from '@opentelemetry/api';
import { trace } from '@opentelemetry/api';
import { startInactiveSpan, startSpanManual } from '@sentry/core';

/**
* Set up a mock OTEL tracer to allow inter-op with OpenTelemetry emitted spans.
* This is not perfect but handles easy/common use cases.
*/
export function setupOpenTelemetryTracer(): void {
trace.setGlobalTracerProvider(new SentryCloudflareTraceProvider());
}

class SentryCloudflareTraceProvider implements TracerProvider {
private readonly _tracers: Map<string, Tracer> = new Map();

public getTracer(name: string, version?: string, options?: { schemaUrl?: string }): Tracer {
const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;
if (!this._tracers.has(key)) {
this._tracers.set(key, new SentryCloudflareTracer());
}

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._tracers.get(key)!;
}
}

class SentryCloudflareTracer implements Tracer {
public startSpan(name: string, options?: SpanOptions): Span {
return startInactiveSpan({
name,
...options,
attributes: {
...options?.attributes,
'sentry.cloudflare_tracer': true,
},
});
}

/**
* NOTE: This does not handle `context` being passed in. It will always put spans on the current scope.
*/
public startActiveSpan<F extends (span: Span) => unknown>(name: string, fn: F): ReturnType<F>;
public startActiveSpan<F extends (span: Span) => unknown>(name: string, options: SpanOptions, fn: F): ReturnType<F>;
public startActiveSpan<F extends (span: Span) => unknown>(
name: string,
options: SpanOptions,
context: Context,
fn: F,
): ReturnType<F>;
public startActiveSpan<F extends (span: Span) => unknown>(
name: string,
options: unknown,
context?: unknown,
fn?: F,
): ReturnType<F> {
const opts = (typeof options === 'object' && options !== null ? options : {}) as SpanOptions;

const spanOpts = {
name,
...opts,
attributes: {
...opts.attributes,
'sentry.cloudflare_tracer': true,
},
};

const callback = (
typeof options === 'function'
? options
: typeof context === 'function'
? context
: typeof fn === 'function'
? fn
: // eslint-disable-next-line @typescript-eslint/no-empty-function
() => {}
) as F;

// In OTEL the semantic matches `startSpanManual` because spans are not auto-ended
return startSpanManual(spanOpts, callback) as ReturnType<F>;
}
}
12 changes: 12 additions & 0 deletions packages/cloudflare/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import type { CloudflareClientOptions, CloudflareOptions } from './client';
import { CloudflareClient } from './client';
import { fetchIntegration } from './integrations/fetch';
import { setupOpenTelemetryTracer } from './opentelemetry/tracer';
import { makeCloudflareTransport } from './transport';
import { defaultStackParser } from './vendor/stacktrace';

Expand Down Expand Up @@ -50,5 +51,16 @@ export function init(options: CloudflareOptions): CloudflareClient | undefined {
transport: options.transport || makeCloudflareTransport,
};

/**
* The Cloudflare SDK is not OpenTelemetry native, however, we set up some OpenTelemetry compatibility
* via a custom trace provider.
* This ensures that any spans emitted via `@opentelemetry/api` will be captured by Sentry.
* HOWEVER, big caveat: This does not handle custom context handling, it will always work off the current scope.
* This should be good enough for many, but not all integrations.
*/
if (!options.skipOpenTelemetrySetup) {
setupOpenTelemetryTracer();
}

return initAndBind(CloudflareClient, clientOptions) as CloudflareClient;
}
145 changes: 145 additions & 0 deletions packages/cloudflare/test/opentelemetry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { trace } from '@opentelemetry/api';
import type { TransactionEvent } from '@sentry/core';
import { startSpan } from '@sentry/core';
import { beforeEach, describe, expect, test } from 'vitest';
import { init } from '../src/sdk';
import { resetSdk } from './testUtils';

describe('opentelemetry compatibility', () => {
beforeEach(() => {
resetSdk();
});

test('should not capture spans emitted via @opentelemetry/api when skipOpenTelemetrySetup is true', async () => {
const transactionEvents: TransactionEvent[] = [];

const client = init({
dsn: 'https://username@domain/123',
tracesSampleRate: 1,
skipOpenTelemetrySetup: true,
beforeSendTransaction: event => {
transactionEvents.push(event);
return null;
},
});

const tracer = trace.getTracer('test');
const span = tracer.startSpan('test');
span.end();

await client!.flush();

tracer.startActiveSpan('test 2', { attributes: { 'test.attribute': 'test' } }, span2 => {
const span = tracer.startSpan('test 3', { attributes: { 'test.attribute': 'test2' } });
span.end();
span2.end();
});

await client!.flush();

expect(transactionEvents).toHaveLength(0);
});

test('should capture spans emitted via @opentelemetry/api', async () => {
const transactionEvents: TransactionEvent[] = [];

const client = init({
dsn: 'https://username@domain/123',
tracesSampleRate: 1,
beforeSendTransaction: event => {
transactionEvents.push(event);
return null;
},
});

const tracer = trace.getTracer('test');
const span = tracer.startSpan('test');
span.end();

await client!.flush();

tracer.startActiveSpan('test 2', { attributes: { 'test.attribute': 'test' } }, span2 => {
const span = tracer.startSpan('test 3', { attributes: { 'test.attribute': 'test2' } });
span.end();
span2.end();
});

await client!.flush();

expect(transactionEvents).toHaveLength(2);
const [transactionEvent, transactionEvent2] = transactionEvents;

expect(transactionEvent?.spans?.length).toBe(0);
expect(transactionEvent?.transaction).toBe('test');
expect(transactionEvent?.contexts?.trace?.data).toEqual({
'sentry.cloudflare_tracer': true,
'sentry.origin': 'manual',
'sentry.sample_rate': 1,
'sentry.source': 'custom',
});

expect(transactionEvent2?.spans?.length).toBe(1);
expect(transactionEvent2?.transaction).toBe('test 2');
expect(transactionEvent2?.contexts?.trace?.data).toEqual({
'sentry.cloudflare_tracer': true,
'sentry.origin': 'manual',
'sentry.sample_rate': 1,
'sentry.source': 'custom',
'test.attribute': 'test',
});

expect(transactionEvent2?.spans).toEqual([
expect.objectContaining({
description: 'test 3',
data: {
'sentry.cloudflare_tracer': true,
'sentry.origin': 'manual',
'test.attribute': 'test2',
},
}),
]);
});

test('opentelemetry spans should interop with Sentry spans', async () => {
const transactionEvents: TransactionEvent[] = [];

const client = init({
dsn: 'https://username@domain/123',
tracesSampleRate: 1,
beforeSendTransaction: event => {
transactionEvents.push(event);
return null;
},
});

const tracer = trace.getTracer('test');

startSpan({ name: 'sentry span' }, () => {
const span = tracer.startSpan('otel span');
span.end();
});

await client!.flush();

expect(transactionEvents).toHaveLength(1);
const [transactionEvent] = transactionEvents;

expect(transactionEvent?.spans?.length).toBe(1);
expect(transactionEvent?.transaction).toBe('sentry span');
expect(transactionEvent?.contexts?.trace?.data).toEqual({
'sentry.origin': 'manual',
'sentry.sample_rate': 1,
'sentry.source': 'custom',
});

expect(transactionEvent?.spans).toEqual([
expect.objectContaining({
description: 'otel span',
data: {
'sentry.cloudflare_tracer': true,
'sentry.origin': 'manual',
},
}),
]);
});
});
7 changes: 6 additions & 1 deletion packages/cloudflare/test/sdk.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import * as SentryCore from '@sentry/core';
import { describe, expect, test, vi } from 'vitest';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { CloudflareClient } from '../src/client';
import { init } from '../src/sdk';
import { resetSdk } from './testUtils';

describe('init', () => {
beforeEach(() => {
resetSdk();
});

test('should call initAndBind with the correct options', () => {
const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind');
const client = init({});
Expand Down
21 changes: 21 additions & 0 deletions packages/cloudflare/test/testUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { context, propagation, trace } from '@opentelemetry/api';
import { getCurrentScope, getGlobalScope, getIsolationScope } from '@sentry/core';

function resetGlobals(): void {
getCurrentScope().clear();
getCurrentScope().setClient(undefined);
getIsolationScope().clear();
getGlobalScope().clear();
}

function cleanupOtel(): void {
// Disable all globally registered APIs
trace.disable();
context.disable();
propagation.disable();
}

export function resetSdk(): void {
resetGlobals();
cleanupOtel();
}
Loading