Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as Sentry from '@sentry/cloudflare';

interface Env {
SENTRY_DSN: string;
}

export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
}),
{
async fetch(_request, _env, _ctx) {
throw new Error('Error with a server name');
},
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { expect, it } from 'vitest';
import { eventEnvelope } from '../../expect';
import { createRunner } from '../../runner';

it('uses the SENTRY_NAME env variable as server_name', async ({ signal }) => {
const runner = createRunner(__dirname)
.expect(
eventEnvelope(
{
level: 'error',
server_name: 'my-worker',
exception: {
values: [
{
type: 'Error',
value: 'Error with a server name',
stacktrace: {
frames: expect.any(Array),
},
mechanism: { type: 'auto.http.cloudflare', handled: false },
},
],
},
request: {
cookies: {},
headers: expect.any(Object),
method: 'GET',
url: expect.any(String),
},
},
{ includeTransaction: false },
),
)
.start(signal);
await runner.makeRequest('get', '/', { expectError: true });
await runner.completed();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "worker-name",
"compatibility_date": "2025-06-17",
"main": "index.ts",
"compatibility_flags": ["nodejs_compat"],
"vars": {
"SENTRY_NAME": "my-worker",
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as Sentry from '@sentry/cloudflare';

interface Env {
SENTRY_DSN: string;
}

// Wrapped by hand, so the plugin only adds the worker name and compatibility date to this entry.
export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
}),
{
async fetch() {
throw new Error('Error with the worker info');
},
} satisfies ExportedHandler<Env>,
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { expect, it } from 'vitest';
import { eventEnvelope } from '../../../expect';
import { createRunner } from '../../../runner';

it('uses the wrangler name as server_name and the compatibility date as runtime version for a hand-wrapped handler', async ({
signal,
}) => {
const runner = createRunner(__dirname)
.expect(
eventEnvelope(
{
level: 'error',
server_name: 'cloudflare-vite-autoinstrument-worker-info',
contexts: { runtime: { name: 'cloudflare', version: '2025-06-17' } },
exception: {
values: [
{
type: 'Error',
value: 'Error with the worker info',
stacktrace: {
frames: expect.any(Array),
},
mechanism: { type: 'auto.http.cloudflare', handled: false },
},
],
},
request: {
cookies: {},
headers: expect.any(Object),
method: 'GET',
url: expect.any(String),
},
},
{ includeTransaction: false },
),
)
.start(signal);
await runner.makeRequest('get', '/', { expectError: true });
await runner.completed();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { cloudflare } from '@cloudflare/vite-plugin';
import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [cloudflare(), sentryCloudflareVitePlugin()],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "../../../node_modules/wrangler/config-schema.json",
"name": "cloudflare-vite-autoinstrument-worker-info",
"main": "index.ts",
"compatibility_date": "2025-06-17",
"compatibility_flags": ["nodejs_compat"],
}
20 changes: 17 additions & 3 deletions packages/cloudflare/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
_INTERNAL_flushMetricsBuffer,
applySdkMetadata,
debug,
GLOBAL_OBJ,
spanIsSampled,
spanStreamingIntegration,
} from '@sentry/core';
Expand All @@ -20,6 +21,14 @@ declare const __SENTRY_TRACING__: boolean;

const SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';

type GlobalWithWorkerInfo = typeof GLOBAL_OBJ & {
/**
* The `name` and `compatibility_date` of the wrangler config. Only set when the Worker is built
* with `sentryCloudflareVitePlugin`.
*/
__SENTRY_CLOUDFLARE_WORKER__?: { name?: string; compatibilityDate?: string };
};

/**
* The Sentry Cloudflare SDK Client.
*
Expand Down Expand Up @@ -58,13 +67,15 @@ export class CloudflareClient extends ServerRuntimeClient {
applySdkMetadata(options, 'cloudflare');
options._metadata = options._metadata || {};
const { flushLock, ...serverOptions } = options;
const workerInfo = (GLOBAL_OBJ as GlobalWithWorkerInfo).__SENTRY_CLOUDFLARE_WORKER__;

const clientOptions: ServerRuntimeClientOptions = {
...serverOptions,
platform: 'javascript',
// TODO: Grab version information
runtime: { name: 'cloudflare' },
// TODO: Add server name
// workerd exposes no version at runtime (`navigator.userAgent` is always `Cloudflare-Workers`).
// The compatibility date selects the workerd behavior of the Worker, so it is the version.
runtime: { name: 'cloudflare', version: workerInfo?.compatibilityDate },
serverName: serverOptions.serverName ?? workerInfo?.name,
_flushInterval: 0,
};

Expand Down Expand Up @@ -508,6 +519,9 @@ interface BaseCloudflareOptions {
* Sets an optional server name (device name).
*
* This is useful for identifying which server or instance is sending events.
*
* @default the `SENTRY_NAME` variable of `env`, else the `name` of the wrangler config when you
* build with `sentryCloudflareVitePlugin`
*/
serverName?: string;

Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export function getFinalOptions(userOptions: CloudflareOptions = {}, env: unknow
...userOptions,
dsn: userOptions.dsn ?? getEnvVar(env, 'SENTRY_DSN'),
environment: userOptions.environment ?? getEnvVar(env, 'SENTRY_ENVIRONMENT'),
serverName: userOptions.serverName ?? getEnvVar(env, 'SENTRY_NAME'),
tracesSampleRate: isFinite(tracesSampleRate) ? tracesSampleRate : undefined,
debug: userOptions.debug ?? envToBool(getEnvVar(env, 'SENTRY_DEBUG')),
tunnel: userOptions.tunnel ?? getEnvVar(env, 'SENTRY_TUNNEL'),
Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/vite/autoInstrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ export function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPa
optionsImport,
sameWorkerBindings: wranglerConfig.sameWorkerBindings,
sentryModule,
workerInfo: { name: wranglerConfig.name, compatibilityDate: wranglerConfig.compatibilityDate },
});

const wrappedClasses = result?.wrappedClasses ?? new Set<string>();
Expand Down
3 changes: 3 additions & 0 deletions packages/cloudflare/src/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export interface SentryCloudflareVitePluginOptions {
* Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to
* other workers stay opt-in, their receivers may not run Sentry.
*
* The plugin also sets the `name` of your wrangler config as the default `serverName` and the
* `compatibility_date` as the runtime version, also for handlers you wrap yourself.
*
* @default true
*/
autoInstrumentation?: boolean;
Expand Down
38 changes: 25 additions & 13 deletions packages/cloudflare/src/vite/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { detectWorkerEntrypointClasses } from './workerEntrypoint';

const MERGED_OPTIONS_IDENTIFIER = '__SENTRY_OPTIONS__';

// Read by `CloudflareClient` for the default `serverName` and the runtime version.
const WORKER_INFO_GLOBAL = '__SENTRY_CLOUDFLARE_WORKER__';

// ---------------------------------------------------------------------------
// Minimal ESTree node types for the AST nodes we inspect.
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -122,6 +125,12 @@ export interface TransformContext {
sentryModule?: string;
/** @see {@link import('./wranglerConfig').WranglerConfig.sameWorkerBindings} */
sameWorkerBindings?: readonly SameWorkerBinding[];
/**
* The Worker name and compatibility date, stored on `globalThis` as the default `serverName` and
* the runtime version. The entry stores them also when nothing is wrapped, so hand-wrapped
* handlers get them too.
*/
workerInfo?: { name?: string; compatibilityDate?: string };
}

export interface TransformResult {
Expand Down Expand Up @@ -149,8 +158,9 @@ export interface TransformResult {
* {@link TransformResult.wrappedClasses}.
*
* Exported (rather than inlined into the plugin) so it can be unit-tested with a
* plain AST and no Vite context. Returns `undefined` when nothing was wrapped and
* there are no already-manually-wrapped classes to report.
* plain AST and no Vite context. Returns `undefined` when nothing was wrapped,
* there are no already-manually-wrapped classes to report, and there is no
* {@link TransformContext.workerInfo} to store.
*/
export function applyAutoInstrumentTransforms(
code: string,
Expand Down Expand Up @@ -192,20 +202,22 @@ export function applyAutoInstrumentTransforms(
}
}

if (!state.needsImport) {
// Nothing was rewritten. Still surface any classes found already wrapped
// manually (via `wrappedClasses`) so the caller doesn't warn about them;
// return undefined only when there was nothing to report either.
if (wrappedClasses.size === 0) return undefined;
return { code, map: ms.generateMap({ hires: true }), wrappedClasses };
if (state.needsImport) {
// `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.
if (sameWorkerBindings.length > 0) {
ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
}
if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\n`);
}

// `prepend` inserts before earlier prepends, yielding: Sentry import, options import, declaration.
if (sameWorkerBindings.length > 0) {
ms.prepend(buildMergedOptionsDeclaration(sameWorkerBindings, ctx.optionsFn, state));
if (ctx.workerInfo?.name || ctx.workerInfo?.compatibilityDate) {
ms.prepend(`globalThis.${WORKER_INFO_GLOBAL} = ${JSON.stringify(ctx.workerInfo)};\n`);
} else if (!state.needsImport && wrappedClasses.size === 0) {
// Nothing was rewritten. Classes found already wrapped manually are still
// reported (via `wrappedClasses`) so the caller doesn't warn about them.
return undefined;
}
if (ctx.optionsImport) ms.prepend(ctx.optionsImport);
ms.prepend(`import * as __SENTRY__ from '${ctx.sentryModule ?? '@sentry/cloudflare'}';\n`);

return {
code: ms.toString(),
Expand Down
10 changes: 10 additions & 0 deletions packages/cloudflare/src/vite/wranglerConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ import { type Unstable_Config, unstable_readConfig } from 'wrangler';
* about.
*/
export interface WranglerConfig {
/**
* The name of the deployed Worker, `<name>-<environment>` for a wrangler environment.
*/
name?: string;
/**
* The `compatibility_date` that selects the workerd behavior of the Worker.
*/
compatibilityDate?: string;
/**
* An absolute path when `main` names a JS or TS file, otherwise the
* original value (a package export or virtual module) for Vite to resolve.
Expand Down Expand Up @@ -83,6 +91,8 @@ export function resolveWranglerConfig(

return {
config: {
name: raw.name,
compatibilityDate: raw.compatibility_date,
main: raw.main && ENTRY_FILE_REGEX.test(raw.main) ? resolve(configDir, raw.main) : raw.main,
durableObjects: collectClassBindings(raw.durable_objects?.bindings),
workflows: collectClassBindings(raw.workflows),
Expand Down
36 changes: 35 additions & 1 deletion packages/cloudflare/test/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';
import { CloudflareClient, type CloudflareClientOptions } from '../src/client';
import { makeFlushLock } from '../src/flush';
Expand Down Expand Up @@ -225,6 +225,40 @@ describe('CloudflareClient', () => {
});
});

describe('worker info stored by the Vite plugin', () => {
const globalWithWorkerInfo = globalThis as {
__SENTRY_CLOUDFLARE_WORKER__?: { name?: string; compatibilityDate?: string };
};

afterEach(() => {
delete globalWithWorkerInfo.__SENTRY_CLOUDFLARE_WORKER__;
});

it('uses the worker name as serverName and the compatibility date as runtime version', () => {
globalWithWorkerInfo.__SENTRY_CLOUDFLARE_WORKER__ = { name: 'my-worker', compatibilityDate: '2025-06-17' };

const client = new CloudflareClient(MOCK_CLIENT_OPTIONS);

expect(client.getOptions().serverName).toBe('my-worker');
expect(client.getOptions().runtime).toEqual({ name: 'cloudflare', version: '2025-06-17' });
});

it('prefers the serverName option over the worker name', () => {
globalWithWorkerInfo.__SENTRY_CLOUDFLARE_WORKER__ = { name: 'my-worker' };

const client = new CloudflareClient({ ...MOCK_CLIENT_OPTIONS, serverName: 'user-server' });

expect(client.getOptions().serverName).toBe('user-server');
});

it('has no serverName and no runtime version without stored worker info', () => {
const client = new CloudflareClient(MOCK_CLIENT_OPTIONS);

expect(client.getOptions().serverName).toBeUndefined();
expect(client.getOptions().runtime).toEqual({ name: 'cloudflare' });
});
});

describe('flush()', () => {
it('calls transport flush with the given timeout', async () => {
const client = new CloudflareClient(MOCK_CLIENT_OPTIONS);
Expand Down
18 changes: 18 additions & 0 deletions packages/cloudflare/test/options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,24 @@ describe('getFinalOptions', () => {
expect(result.environment).toBe('staging');
});

it('uses SENTRY_NAME from env when user serverName is undefined', () => {
const userOptions = { dsn: 'test-dsn' };
const env = { SENTRY_NAME: 'my-worker' };

const result = getFinalOptions(userOptions, env);

expect(result.serverName).toBe('my-worker');
});

it('prefers user serverName over env SENTRY_NAME', () => {
const userOptions = { dsn: 'test-dsn', serverName: 'user-server' };
const env = { SENTRY_NAME: 'my-worker' };

const result = getFinalOptions(userOptions, env);

expect(result.serverName).toBe('user-server');
});

it('uses SENTRY_TRACES_SAMPLE_RATE from env when user tracesSampleRate is undefined', () => {
const userOptions = { dsn: 'test-dsn' };
const env = { SENTRY_TRACES_SAMPLE_RATE: '0.5' };
Expand Down
Loading
Loading