diff --git a/packages/nuxt/src/server/sdk.ts b/packages/nuxt/src/server/sdk.ts index 36e0f1179bea..5bc7e354a054 100644 --- a/packages/nuxt/src/server/sdk.ts +++ b/packages/nuxt/src/server/sdk.ts @@ -12,7 +12,7 @@ import { getClient, isClientClosed, } from '@sentry/core'; -import { init as initNode } from '@sentry/node'; +import { init as initNode, nitroIntegration } from '@sentry/node'; import { getNuxtBuildAssetsPath, getNuxtPublicFilePaths } from '../common/buildAssets'; import { DEBUG_BUILD } from '../common/debug-build'; import { @@ -60,9 +60,12 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { // runtime-flags module sets the global flag for the (usual) externalized case. const envFallback = isDevBuild || isNuxtDevRuntime() ? DEV_ENVIRONMENT : DEFAULT_ENVIRONMENT; + const userOptions = _INTERNAL_captureOptionsSetByUser(options); + const sentryOptions = { environment: options.environment ?? process.env.SENTRY_ENVIRONMENT ?? envFallback, - ..._INTERNAL_captureOptionsSetByUser(options), + ...userOptions, + integrations: withNuxtNitroIntegration(userOptions.integrations), ignoreSpans: [ ...(options.ignoreSpans || []), ...getBuildAssetRequestFilters(getNuxtBuildAssetsPath()), @@ -85,6 +88,31 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { return client; } +/** + * Swaps the default Nitro integration for one without middleware spans, storage spans and `Server-Timing` headers. + * The Nuxt SDK already covers these, so with Nitro's tracing channels on, each operation would get two spans. + * + * It wraps `integrations` and not `defaultIntegrations`, because only `initNode` resolves the defaults correctly + * (it also reads `SENTRY_TRACES_SAMPLE_RATE`). + */ +function withNuxtNitroIntegration( + userIntegrations: SentryNuxtServerOptions['integrations'], +): NonNullable { + // Keep the SDK spans, not the channel spans. Nitro v2 has no channels, and h3 does not tell which middleware ran. + const nuxtNitroIntegration = nitroIntegration({ middleware: false, storage: false, serverTiming: false }); + + return defaultIntegrations => { + const integrations = defaultIntegrations.map(integration => + // The spread keeps core's default-instance flag, so a `nitroIntegration` from the user still wins. + integration.name === nuxtNitroIntegration.name ? { ...integration, ...nuxtNitroIntegration } : integration, + ); + + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations ?? [])]; + }; +} + /** * Ignores files from `public/` that the HTTP integration's static asset filter misses, such as `.pdf` and `.txt` files. * Matches exact paths, because a route can share a prefix with a public dir. diff --git a/packages/nuxt/test/server/sdk.test.ts b/packages/nuxt/test/server/sdk.test.ts index 11c660e1dae7..5978d3f63597 100644 --- a/packages/nuxt/test/server/sdk.test.ts +++ b/packages/nuxt/test/server/sdk.test.ts @@ -152,6 +152,75 @@ describe('Nuxt Server SDK', () => { expect(callArgs?.defaultIntegrations).toBe(false); }); + describe('Nitro integration', () => { + it('keeps the integrations of a user `integrations` array', () => { + const checkoutIntegration = { name: 'CheckoutAnalytics' }; + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [checkoutIntegration], + }); + + expect(client?.getIntegrationByName('CheckoutAnalytics')).toBe(checkoutIntegration); + expect(client?.getIntegrationByName('Nitro')).toBeDefined(); + }); + + it('applies a user `integrations` function to the default integrations', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => defaults.filter(integration => integration.name !== 'Console'), + }); + + expect(client?.getIntegrationByName('Console')).toBeUndefined(); + expect(client?.getIntegrationByName('Nitro')).toBeDefined(); + }); + + it('uses a `nitroIntegration` from the user instead of its own', () => { + const userNitroIntegration = SentryNode.nitroIntegration({ serverTiming: false }); + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [userNitroIntegration], + }); + + expect(client?.getIntegrationByName('Nitro')).toBe(userNitroIntegration); + }); + + it('uses a `nitroIntegration` that a user `integrations` function puts before the defaults', () => { + const userNitroIntegration = SentryNode.nitroIntegration({ serverTiming: false }); + + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => [userNitroIntegration, ...defaults], + }); + + expect(client?.getIntegrationByName('Nitro')).toBe(userNitroIntegration); + }); + + it('reports the integrations that a user `integrations` function adds and removes', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => [ + ...defaults.filter(integration => integration.name !== 'Console'), + { name: 'CheckoutAnalytics' }, + ], + }); + + expect(client?.getOptions()._metadata?.integrationsSetByUser).toEqual(['CheckoutAnalytics']); + expect(client?.getOptions()._metadata?.removedDefaultIntegrations).toEqual(['Console']); + }); + + it('adds no Nitro integration when the default integrations are off', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + defaultIntegrations: false, + }); + + expect(client).toBeDefined(); + expect(client?.getIntegrationByName('Nitro')).toBeUndefined(); + }); + }); + describe('environment option', () => { const originalEnv = process.env.SENTRY_ENVIRONMENT; diff --git a/packages/nuxt/test/server/tracingChannels.test.ts b/packages/nuxt/test/server/tracingChannels.test.ts new file mode 100644 index 000000000000..f29962fb3105 --- /dev/null +++ b/packages/nuxt/test/server/tracingChannels.test.ts @@ -0,0 +1,136 @@ +/** @vitest-environment node */ +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { CACHE_GET, CACHE_PUT, CACHE_REMOVE, HANDLER, HTTP_SERVER, MIDDLEWARE } from '@sentry/conventions/op'; +import type { Client, StreamedSpanJSON } from '@sentry/core'; +import { createTransport, getCurrentScope, spanToJSON, startNewTrace, startSpan } from '@sentry/core'; +import { defineHandler, H3 } from 'nitro/h3'; +import type { Driver, Storage } from 'unstorage'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { wrapMiddlewareHandlerWithSentry } from '../../src/runtime/hooks/wrapMiddlewareHandler'; +import { createStoragePlugin } from '../../src/runtime/utils/instrumentStorage'; +import { init } from '../../src/server'; + +type TestStorage = Pick; + +/** + * Imports from the `h3` and `unstorage` versions of the installed Nitro v3, which publish the tracing channels. + * The `h3` and `unstorage` dependencies of this package are the Nitro v2 versions. Nothing checks `TModule`. + */ +const nitroRequire = createRequire(createRequire(import.meta.url).resolve('nitro/package.json')); +function importFromNitro(specifier: string): Promise { + return import(pathToFileURL(nitroRequire.resolve(specifier)).href); +} + +interface SpanSummary { + op: unknown; + name: string; + origin: unknown; + parentOp: unknown; +} + +function summarize(span: StreamedSpanJSON, spans: StreamedSpanJSON[]): SpanSummary { + const parent = spans.find(candidate => candidate.span_id === span.parent_span_id); + return { + op: span.attributes[SENTRY_OP], + name: span.name, + origin: span.attributes[SENTRY_ORIGIN], + parentOp: parent?.attributes[SENTRY_OP], + }; +} + +// Like a Nuxt app on Nitro v3 with `tracingChannel: true`. +// The subscribers stay on the process-wide channels, so all tests share one client. +describe('Nuxt server SDK with the Nitro v3 tracing channels on', () => { + let client: Client; + let app: H3; + const endedSpans: StreamedSpanJSON[] = []; + + /** Makes the `http.server` root span, as the HTTP integration of the runtime does in a real server. */ + async function request(path: string): Promise<{ response: Response; spans: SpanSummary[] }> { + const { response, traceId } = await startNewTrace(() => + startSpan({ name: 'GET', op: HTTP_SERVER }, async rootSpan => ({ + response: await app.request(path), + traceId: spanToJSON(rootSpan).trace_id, + })), + ); + + const spans = endedSpans.filter(span => span.trace_id === traceId); + return { response, spans: spans.map(span => summarize(span, spans)) }; + } + + beforeAll(async () => { + const { tracingPlugin } = await importFromNitro<{ tracingPlugin: () => (app: H3) => void }>('h3/tracing'); + const { createStorage } = await importFromNitro<{ createStorage: () => TestStorage }>('unstorage'); + const { default: memoryDriver } = await importFromNitro<{ default: () => Driver }>('unstorage/drivers/memory'); + const { withTracing } = await importFromNitro<{ withTracing: (storage: TestStorage) => TestStorage }>( + 'unstorage/tracing', + ); + + const nuxtClient = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + tracesSampleRate: 1, + transport: () => createTransport({ recordDroppedEvent: () => undefined }, () => Promise.resolve({})), + }); + if (!nuxtClient) { + throw new Error('The Nuxt server SDK did not initialize.'); + } + client = nuxtClient; + client.on('spanEnd', span => endedSpans.push(spanToJSON(span))); + + const storage = createStorage(); + storage.mount('sessions', memoryDriver()); + createStoragePlugin(() => storage, ['sessions']); + const tracedStorage = withTracing(storage); + + app = new H3(); + tracingPlugin()(app); + app.use(defineHandler(wrapMiddlewareHandlerWithSentry(() => undefined, 'auth'))); + app.get('/api/sessions/:id', async event => { + const key = `sessions:${event.context.params?.id}`; + await tracedStorage.setItem(key, { user: 'ada' }); + const session = await tracedStorage.getItem(key); + await tracedStorage.removeItem(key); + return { session }; + }); + }); + + afterAll(async () => { + await client.close(); + getCurrentScope().setClient(undefined); + }); + + it('creates one span for a server middleware, from the SDK wrapper', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => span.op === MIDDLEWARE)).toEqual([ + { op: MIDDLEWARE, name: 'auth', origin: 'auto.middleware.nuxt', parentOp: HTTP_SERVER }, + ]); + }); + + it('creates one span for each storage call, from the SDK storage instrumentation', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => String(span.op).startsWith('cache.'))).toEqual([ + { op: CACHE_PUT, name: CACHE_PUT, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + { op: CACHE_GET, name: CACHE_GET, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + { op: CACHE_REMOVE, name: CACHE_REMOVE, origin: 'auto.cache.nuxt', parentOp: HANDLER }, + ]); + }); + + it('keeps the handler span of the h3 channel, which has no SDK source', async () => { + const { spans } = await request('/api/sessions/42?include=profile'); + + expect(spans.filter(span => span.op === HANDLER)).toEqual([ + { op: HANDLER, name: 'GET /api/sessions/:id', origin: 'auto.http.nitro.h3', parentOp: HTTP_SERVER }, + ]); + }); + + it('sets no Server-Timing header on the response', async () => { + const { response } = await request('/api/sessions/42?include=profile'); + + expect(response.status).toBe(200); + expect(response.headers.get('Server-Timing')).toBeNull(); + }); +}); diff --git a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts index cf6edae6a546..40b9bb937850 100644 --- a/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts +++ b/packages/server-utils/src/integrations/nitro/captureTracingEvents.ts @@ -28,14 +28,14 @@ type GlobalWithTraceChannels = typeof GLOBAL_OBJ & { /** * Captures tracing events emitted by Nitro tracing channels. */ -export function captureTracingEvents(): void { +export function captureTracingEvents(options: { middleware: boolean }): void { // Resolved at call time: bundlers may evaluate this module before `GLOBAL_OBJ` is initialized. const globalWithTraceChannels = GLOBAL_OBJ as GlobalWithTraceChannels; if (globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__) { return; } - setupH3TracingChannels(); + setupH3TracingChannels(options); setupSrvxTracingChannels(); globalWithTraceChannels.__SENTRY_NITRO_HTTP_CHANNELS_INSTRUMENTED__ = true; } @@ -98,7 +98,7 @@ function getParameterizedRoute(event: NitroH3Event): string | undefined { return routePath; } -function setupH3TracingChannels(): void { +function setupH3TracingChannels(options: { middleware: boolean }): void { // Bail if this is not available if (!diagnosticsChannel.tracingChannel) { return; @@ -107,6 +107,10 @@ function setupH3TracingChannels(): void { bindTracingChannelToSpan( diagnosticsChannel.tracingChannel('h3.request'), data => { + if (data.type === 'middleware' && !options.middleware) { + return undefined; + } + const method = data.event.req.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK; // The route lives on the request's `http.server` root span, so the route handler only gets a diff --git a/packages/server-utils/src/integrations/nitro/index.ts b/packages/server-utils/src/integrations/nitro/index.ts index 860d0993ef3e..1b9e8085eac4 100644 --- a/packages/server-utils/src/integrations/nitro/index.ts +++ b/packages/server-utils/src/integrations/nitro/index.ts @@ -7,6 +7,13 @@ import { captureServerTimingHeaders } from './setServerTimingHeaders'; const INTEGRATION_NAME = 'Nitro' as const; export interface NitroIntegrationOptions { + /** + * Create `middleware` spans for h3 middleware. + * + * @default true + */ + middleware?: boolean; + /** * Set `Server-Timing` response headers carrying the current `sentry-trace`/`baggage`, so the browser * SDK can connect a pageload trace to the backend trace. @@ -24,12 +31,12 @@ export interface NitroIntegrationOptions { } const _nitroIntegration = ((options: NitroIntegrationOptions = {}) => { - const { serverTiming = true, storage = true } = options; + const { middleware = true, serverTiming = true, storage = true } = options; return { name: INTEGRATION_NAME, setupOnce() { - captureTracingEvents(); + captureTracingEvents({ middleware }); if (storage) { captureStorageEvents(); diff --git a/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts b/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts new file mode 100644 index 000000000000..56bd3d3e16ce --- /dev/null +++ b/packages/server-utils/test/integrations/nitro/captureTracingEvents.test.ts @@ -0,0 +1,80 @@ +import { tracingChannel } from 'node:diagnostics_channel'; +import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { HANDLER, HTTP_SERVER } from '@sentry/conventions/op'; +import type { StreamedSpanJSON } from '@sentry/core'; +import { + createTransport, + getActiveSpan, + getCurrentScope, + initAndBind, + resolvedSyncPromise, + setAsyncContextStrategy, + spanToJSON, + startSpan, +} from '@sentry/core'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { setAsyncLocalStorageAsyncContextStrategy } from '../../../src/async-context'; +import { captureTracingEvents } from '../../../src/integrations/nitro/captureTracingEvents'; +import type { H3TracingRequestEvent } from '../../../src/integrations/nitro/nitroTypes'; +import { TestClient } from '../../mocks/client'; + +const h3RequestChannel = tracingChannel('h3.request'); + +function createH3Event(): H3TracingRequestEvent['event'] { + return { + url: new URL('https://shop.example.com/api/users/42?include=profile'), + req: { method: 'GET' }, + context: { matchedRoute: { route: '/api/users/:id' }, params: { id: '42' } }, + }; +} + +/** Publishes an `h3.request` event like h3's `tracingPlugin`, and returns the span that is active inside it. */ +function traceH3Request(type: H3TracingRequestEvent['type']): Promise { + return startSpan({ name: 'GET /api/users/42', op: HTTP_SERVER }, () => + h3RequestChannel.tracePromise( + async () => { + const activeSpan = getActiveSpan(); + return activeSpan && spanToJSON(activeSpan); + }, + { type, event: createH3Event() }, + ), + ); +} + +// The subscribers stay on the process-wide channel, so a file can set them up only once. +// That is why `middleware: true` has no test here. +describe('captureTracingEvents with `middleware: false`', () => { + beforeAll(() => { + setAsyncLocalStorageAsyncContextStrategy(); + initAndBind(TestClient, { + dsn: 'https://username@domain/123', + integrations: [], + sendClientReports: false, + stackParser: () => [], + tracesSampleRate: 1, + transport: () => createTransport({ recordDroppedEvent: () => undefined }, () => resolvedSyncPromise({})), + }); + + captureTracingEvents({ middleware: false }); + }); + + afterAll(() => { + getCurrentScope().setClient(undefined); + setAsyncContextStrategy(undefined); + }); + + it('starts no span for an h3 middleware', async () => { + const activeSpan = await traceH3Request('middleware'); + + expect(activeSpan?.name).toBe('GET /api/users/42'); + expect(activeSpan?.attributes[SENTRY_OP]).toBe(HTTP_SERVER); + }); + + it('still starts a handler span for an h3 route', async () => { + const activeSpan = await traceH3Request('route'); + + expect(activeSpan?.name).toBe('GET /api/users/:id'); + expect(activeSpan?.attributes[SENTRY_OP]).toBe(HANDLER); + expect(activeSpan?.attributes[SENTRY_ORIGIN]).toBe('auto.http.nitro.h3'); + }); +}); diff --git a/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts b/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts index 5888f97d8fcb..9cfd41fa812b 100644 --- a/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts +++ b/packages/server-utils/test/integrations/nitro/nitroIntegration.test.ts @@ -17,6 +17,16 @@ describe('nitroIntegration', () => { nitroIntegration().setupOnce!(); expect(captureTracingEvents).toHaveBeenCalledTimes(1); + expect(captureTracingEvents).toHaveBeenCalledWith({ middleware: true }); + expect(captureStorageEvents).toHaveBeenCalledTimes(1); + expect(captureServerTimingHeaders).toHaveBeenCalledTimes(1); + }); + + it('turns off h3 middleware spans when `middleware` is disabled', () => { + nitroIntegration({ middleware: false }).setupOnce!(); + + expect(captureTracingEvents).toHaveBeenCalledTimes(1); + expect(captureTracingEvents).toHaveBeenCalledWith({ middleware: false }); expect(captureStorageEvents).toHaveBeenCalledTimes(1); expect(captureServerTimingHeaders).toHaveBeenCalledTimes(1); });