Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ test.describe('server-side errors', () => {
},
sdk: {
integrations: expect.any(Array),
name: 'sentry.javascript.cloudflare',
name: 'sentry.javascript.astro',
packages: expect.any(Array),
version: expect.any(String),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ import { getRuntime } from '@sentry-internal/test-utils';

export const RUNTIME = getRuntime();

// Only Node inits `@sentry/nestjs`. Bun, Deno and Cloudflare init their runtime's own SDK.
export const SDK_NAME = RUNTIME === 'node' ? 'sentry.javascript.nestjs' : `sentry.javascript.${RUNTIME}`;
// Bun, Deno and Cloudflare init their runtime's own SDK, but
// `nestIntegration()` sets the NestJS SDK name.
export const SDK_NAME = 'sentry.javascript.nestjs';
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ test('Instruments mysql automatically', async ({ baseURL }) => {

const spans = await spansPromise;

const rootSpan = spans.find(span => span.is_segment);
expect(rootSpan!.attributes['sentry.sdk.name']).toEqual({ type: 'string', value: 'sentry.javascript.nuxt' });

// Neither query has a FROM target, so the low-cardinality summary (and streamed
// span name) is just the operation. The raw SQL stays on `db.query.text`.
expect(spans).toContainEqual(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ test('does not instrument the internal `$fetch` of a server-rendered page as its
const serverSpanPaths = spans.filter(span => getSpanOp(span) === 'http.server').map(getUrlPath);
expect(serverSpanPaths).toContain('/');
expect(serverSpanPaths).not.toContain('/api/internal');

const rootSpan = spans.find(span => span.is_segment && getUrlPath(span) === '/');
expect(rootSpan?.attributes['sentry.sdk.name']).toEqual({ type: 'string', value: 'sentry.javascript.nuxt' });
});
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ test('sends a streamed server span for a Worker-rendered route', async ({ page }
expect(serverSpan.name).toBe('GET /');
expect(serverSpan.status).toBe('ok');
expect(serverSpan.trace_id).toMatch(/[a-f0-9]{32}/);
expect(serverSpan.attributes['sentry.sdk.name']).toEqual({
type: 'string',
value: 'sentry.javascript.sveltekit',
});
});

test('captures a server load error thrown in the Worker', async ({ page }) => {
Expand All @@ -38,6 +42,7 @@ test('captures a server load error thrown in the Worker', async ({ page }) => {
value: 'Server Load Error on Cloudflare',
mechanism: expect.objectContaining({ handled: false }),
});
expect(errorEvent.sdk?.name).toBe('sentry.javascript.sveltekit');
});

// `handleError` runs after `wrapRequestHandler` has already returned for streamed responses, so it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@sentry/conventions": "0.33.0",
"@sveltejs/adapter-cloudflare": "^5.0.3",
"@sveltejs/kit": "2.69.1",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test } from '@playwright/test';
import { HTTP_SERVER } from '@sentry/conventions/op';
import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';

test('a real mysql query emits a db span with orchestrion-channel attributes', async ({ baseURL }) => {
Expand All @@ -8,14 +9,20 @@ test('a real mysql query emits a db span with orchestrion-channel attributes', a
// in `wrapRequestHandler`. The query below therefore produces a `db` span on the request's
// http.server trace, with no OTel require-hook (which wouldn't work in workerd).
const traceSpansPromise = collectStreamedSpans('sveltekit-cloudflare-pages', spansOfTrace => {
const hasServerSegment = spansOfTrace.some(span => getSpanOp(span) === 'http.server' && span.is_segment);
const hasServerSegment = spansOfTrace.some(span => getSpanOp(span) === HTTP_SERVER && span.is_segment);
return hasServerSegment && spansOfTrace.some(span => getSpanOp(span) === 'db');
});

const res = await fetch(`${baseURL}/db-mysql`);
expect(res.status).toBe(200);

const traceSpans = await traceSpansPromise;
const serverSpan = traceSpans.find(span => getSpanOp(span) === HTTP_SERVER && span.is_segment);
expect(serverSpan?.attributes['sentry.sdk.name']).toEqual({
type: 'string',
value: 'sentry.javascript.sveltekit',
});

const dbSpans = traceSpans.filter(span => getSpanOp(span) === 'db');

const firstQuery = dbSpans.find(span => span.attributes['db.query.text']?.value === 'SELECT ? + ? AS solution');
Expand All @@ -38,7 +45,7 @@ test('a nested query lands on the same trace (async context restored)', async ({
// parent, proves the channel subscriber restored the parent span across that async boundary
// (otherwise the nested query would start its own trace and never join this one).
const traceSpansPromise = collectStreamedSpans('sveltekit-cloudflare-pages', spansOfTrace => {
const hasServerSegment = spansOfTrace.some(span => getSpanOp(span) === 'http.server' && span.is_segment);
const hasServerSegment = spansOfTrace.some(span => getSpanOp(span) === HTTP_SERVER && span.is_segment);
return hasServerSegment && spansOfTrace.filter(span => getSpanOp(span) === 'db').length >= 2;
});

Expand Down
7 changes: 6 additions & 1 deletion packages/astro/src/integration/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Options } from '@sentry/core';
import { applySdkMetadata, stringifyForCodeInjection } from '@sentry/core';
import type { AstroConfig } from 'astro';
import { builtinModules } from 'module';
import { SERVER_INIT_IMPORT } from './serverInit';
Expand Down Expand Up @@ -73,7 +75,10 @@ export function sentryCloudflareVitePlugin({ importServerInit = false } = {}): V
}

const originalExpr = defaultExportMatch[1];
const wrappedExport = `export default withSentry(() => undefined, ${originalExpr});`;
// A client inited from the bindings alone gets the Astro SDK name too.
const sdkOptions: Options = {};
applySdkMetadata(sdkOptions, 'astro', ['astro', 'cloudflare']);
const wrappedExport = `export default withSentry(() => (${stringifyForCodeInjection(sdkOptions)}), ${originalExpr});`;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
const transformedCode = [
...(importServerInit ? [SERVER_INIT_IMPORT.trim()] : []),
"import { withSentry } from '@sentry/cloudflare';",
Expand Down
20 changes: 17 additions & 3 deletions packages/astro/test/integration/cloudflareVitePlugin.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { SDK_VERSION, stringifyForCodeInjection } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { sentryCloudflareVitePlugin } from '../../src/integration/cloudflare';

const OPTIONS = stringifyForCodeInjection({
_metadata: {
sdk: {
name: 'sentry.javascript.astro',
packages: [
{ name: 'npm:@sentry/astro', version: SDK_VERSION },
{ name: 'npm:@sentry/cloudflare', version: SDK_VERSION },
],
version: SDK_VERSION,
},
},
});

function transform(code: string, id: string, options?: { importServerInit?: boolean }) {
const plugin = sentryCloudflareVitePlugin(options) as { transform: (code: string, id: string) => unknown };
return plugin.transform(code, id);
Expand All @@ -14,7 +28,7 @@ describe('sentryCloudflareVitePlugin', () => {
code: [
"import { withSentry } from '@sentry/cloudflare';",
'const _exports = createExports(manifest);',
'export default withSentry(() => undefined, _exports.default);',
`export default withSentry(() => (${OPTIONS}), _exports.default);`,
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
].join('\n'),
map: null,
});
Expand All @@ -35,7 +49,7 @@ describe('sentryCloudflareVitePlugin', () => {
'import { getExportTypes } from "virtual:cloudflare/export-types";',
'import * as mod from "virtual:cloudflare/user-entry";',
'export * from "virtual:cloudflare/user-entry";',
'export default withSentry(() => undefined, mod.default ?? {});',
`export default withSentry(() => (${OPTIONS}), mod.default ?? {});`,
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
'if (import.meta.hot) { import.meta.hot.accept(); }',
].join('\n'),
map: null,
Expand All @@ -50,7 +64,7 @@ describe('sentryCloudflareVitePlugin', () => {
'import "virtual:@sentry/astro/server-init";',
"import { withSentry } from '@sentry/cloudflare';",
'const _exports = createExports(manifest);',
'export default withSentry(() => undefined, _exports.default);',
`export default withSentry(() => (${OPTIONS}), _exports.default);`,
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
].join('\n'),
map: null,
});
Expand Down
11 changes: 10 additions & 1 deletion packages/nestjs/src/integrations/nest.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { defineIntegration } from '@sentry/core';
import { defineIntegration, SDK_VERSION } from '@sentry/core';
import type { NestCronMonitoringOptions } from './cron-monitoring';
import { setCronMonitoringOptions } from './cron-monitoring';
import { subscribeToNestChannels } from './orchestrion-subscriber';

const INTEGRATION_NAME = 'Nest' as const;
const SDK_NAME = 'sentry.javascript.nestjs';

export type NestIntegrationOptions = NestCronMonitoringOptions;

Expand All @@ -18,6 +19,14 @@ export const nestIntegration = defineIntegration((options: NestIntegrationOption
},
setup(client) {
setCronMonitoringOptions(client, options);

// On Bun, Deno and Cloudflare, the runtime's SDK inits the client and this integration is
// added to it. The runtime SDK stays in `packages`.
const sdk = client.getOptions()._metadata?.sdk;
if (sdk && sdk.name !== SDK_NAME) {
sdk.name = SDK_NAME;
sdk.packages = [{ name: 'npm:@sentry/nestjs', version: SDK_VERSION }, ...(sdk.packages || [])];
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
},
};
});
38 changes: 38 additions & 0 deletions packages/nestjs/test/integrations/nest.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import type { Client, Options } from '@sentry/core';
import { applySdkMetadata, SDK_VERSION } from '@sentry/core';
import { describe, expect, it } from 'vitest';
import { isTargetPatched } from '../../src/integrations/helpers';
import { nestIntegration } from '../../src/integrations/nest';
import type { InjectableTarget } from '../../src/integrations/types';

function setupWithRuntimeSdk(name: string, names?: string[]): Options {
const options: Options = {};
applySdkMetadata(options, name, names);
nestIntegration().setup!({ getOptions: () => options } as unknown as Client);
return options;
}

describe('Nest', () => {
describe('isTargetPatched', () => {
it('should return true if target is already patched', () => {
Expand All @@ -15,4 +25,32 @@ describe('Nest', () => {
expect(target.sentryPatchedInjectable).toBe(true);
});
});

describe('SDK metadata', () => {
it.each(['bun', 'deno', 'cloudflare', 'node'])('names the SDK `nestjs` when the %s SDK inits', runtime => {
expect(setupWithRuntimeSdk(runtime)._metadata).toEqual({
sdk: {
name: 'sentry.javascript.nestjs',
packages: [
{ name: 'npm:@sentry/nestjs', version: SDK_VERSION },
{ name: `npm:@sentry/${runtime}`, version: SDK_VERSION },
],
version: SDK_VERSION,
},
});
});

it('keeps the metadata the NestJS SDK set', () => {
expect(setupWithRuntimeSdk('nestjs', ['nestjs', 'node'])._metadata).toEqual({
sdk: {
name: 'sentry.javascript.nestjs',
packages: [
{ name: 'npm:@sentry/nestjs', version: SDK_VERSION },
{ name: 'npm:@sentry/node', version: SDK_VERSION },
],
version: SDK_VERSION,
},
});
});
});
});
27 changes: 15 additions & 12 deletions packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { CloudflareOptions } from '@sentry/cloudflare';
import { getDefaultIntegrations, setAsyncLocalStorageAsyncContextStrategy } from '@sentry/cloudflare';
import { wrapRequestHandler } from '@sentry/cloudflare/request';
import {
applySdkMetadata,
debug,
getDefaultIsolationScope,
getIsolationScope,
Expand All @@ -21,6 +22,18 @@ import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse';
import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check';
import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags';

function getRequestHandlerOptions(cloudflareOptions: CloudflareOptions): CloudflareOptions {
const options: CloudflareOptions = {
// `wrapRequestHandler` only sets up the integrations that work without `nodejs_compat`.
// Nitro's Cloudflare presets require the flag anyway, so opt into the full set.
defaultIntegrations: getDefaultIntegrations(cloudflareOptions),
_extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined,
...cloudflareOptions,
};
applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']);
return options;
}

/**
* Sentry Cloudflare Nitro plugin for when using the "cloudflare-pages" preset in Nuxt.
* This plugin automatically sets up Sentry error monitoring and performance tracking for Cloudflare Pages projects.
Expand Down Expand Up @@ -76,11 +89,7 @@ export const sentryCloudflareNitroPlugin =

return wrapRequestHandler(
{
options: {
defaultIntegrations: getDefaultIntegrations(cloudflareOptions),
_extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined,
...cloudflareOptions,
},
options: getRequestHandlerOptions(cloudflareOptions),
request,
context: runtime.cloudflare.context,
},
Expand Down Expand Up @@ -119,13 +128,7 @@ export const sentryCloudflareNitroPlugin =
});

const requestHandlerOptions = {
// `wrapRequestHandler` only sets up the integrations that work without `nodejs_compat`.
// Nitro's Cloudflare presets require the flag anyway, so opt into the full set.
options: {
defaultIntegrations: getDefaultIntegrations(cloudflareOptions),
_extendsDefaultIntegrations: cloudflareOptions.defaultIntegrations === undefined,
...cloudflareOptions,
},
options: getRequestHandlerOptions(cloudflareOptions),
request,
context: getCloudflareProperties(event).context,
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { CloudflareOptions } from '@sentry/cloudflare';
import { serveTunnelIntegration } from '@sentry/cloudflare';
import { wrapRequestHandler } from '@sentry/cloudflare/request';
import { getTunnelPath } from '@sentry/core';
import { getTunnelPath, SDK_VERSION } from '@sentry/core';
import type { NitroApp } from 'nitropack';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { sentryCloudflareNitroPlugin } from '../../../src/runtime/plugins/sentry-cloudflare.server';
Expand All @@ -12,6 +12,17 @@ vi.mock('@sentry/cloudflare/request', () => ({

const DSN = 'https://public@dsn.ingest.sentry.io/1337';

const NUXT_SDK_METADATA = {
sdk: {
name: 'sentry.javascript.nuxt',
packages: [
{ name: 'npm:@sentry/nuxt', version: SDK_VERSION },
{ name: 'npm:@sentry/cloudflare', version: SDK_VERSION },
],
version: SDK_VERSION,
},
};

async function handleRequest(
options: CloudflareOptions,
{ path = '/api/db-mysql', method = 'GET', body }: { path?: string; method?: string; body?: string } = {},
Expand Down Expand Up @@ -87,4 +98,28 @@ describe('sentryCloudflareNitroPlugin', () => {
);
expect(localFetch).not.toHaveBeenCalled();
});

it('sets the Nuxt SDK metadata', async () => {
await handleRequest({ dsn: DSN });

expect(wrapRequestHandler).toHaveBeenCalledWith(
expect.objectContaining({ options: expect.objectContaining({ _metadata: NUXT_SDK_METADATA }) }),
expect.any(Function),
);
});

it('sets the Nuxt SDK metadata on Nitro v3', async () => {
const nitroApp = { fetch: vi.fn(), hooks: { hook: vi.fn() } } as unknown as NitroApp & {
fetch: (request: Request) => Promise<Response>;
};
sentryCloudflareNitroPlugin({ dsn: DSN })(nitroApp);

const request = Object.assign(new Request('https://example.com/'), { runtime: { cloudflare: { context: {} } } });
await nitroApp.fetch(request);

expect(wrapRequestHandler).toHaveBeenCalledWith(
expect.objectContaining({ options: expect.objectContaining({ _metadata: NUXT_SDK_METADATA }) }),
expect.any(Function),
);
});
});
4 changes: 3 additions & 1 deletion packages/sveltekit/src/worker/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
getDefaultIntegrations as getDefaultCloudflareIntegrations,
setAsyncLocalStorageAsyncContextStrategy,
} from '@sentry/cloudflare';
import { addNonEnumerableProperty } from '@sentry/core';
import { addNonEnumerableProperty, applySdkMetadata } from '@sentry/core';
import type { Handle } from '../server-common/handleTypes';
import { rewriteFramesIntegration } from '../server-common/integrations/rewriteFramesIntegration';
import { svelteKitSpansIntegration } from '../server-common/integrations/svelteKitSpans';
Expand Down Expand Up @@ -32,6 +32,8 @@ export function initCloudflareSentryHandle(options: CloudflareOptions): Handle {
...options,
};

applySdkMetadata(opts, 'sveltekit', ['sveltekit', 'cloudflare']);

setAsyncLocalStorageAsyncContextStrategy();

const handleInitSentry: Handle = ({ event, resolve }) => {
Expand Down
Loading
Loading