diff --git a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts index 8492bbd2c3ee..5cc8fd42a405 100644 --- a/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts +++ b/packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts @@ -20,15 +20,18 @@ import { sentryCaptureErrorHook } from '../hooks/captureErrorHook'; import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse'; import { isCloudflareEntryWrapped } from '../utils/cloudflare-entry'; import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check'; +import { withNuxtTracingChannelIntegration } from '../utils/nuxtTracingChannelIntegration'; import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags'; function getRequestHandlerOptions(cloudflareOptions: CloudflareOptions): CloudflareOptions { + const userOptions = _INTERNAL_captureOptionsSetByUser(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, - ..._INTERNAL_captureOptionsSetByUser(cloudflareOptions), + ...userOptions, + integrations: withNuxtTracingChannelIntegration(userOptions.integrations), }; applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']); return options; diff --git a/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts b/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts new file mode 100644 index 000000000000..780725490579 --- /dev/null +++ b/packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts @@ -0,0 +1,116 @@ +import { CODE_FUNCTION_NAME, ERROR_TYPE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { FUNCTION } from '@sentry/conventions/op'; +import type { Integration, Options, Span } from '@sentry/core'; +import { defineIntegration, getActiveSpan, SPAN_STATUS_ERROR, SPAN_STATUS_OK, startInactiveSpan } from '@sentry/core'; +import type { TracingChannelPayloadWithSpan } from '@sentry/server-utils'; +import { bindTracingChannelToSpan, diagnosticsTracingChannel } from '@sentry/server-utils'; + +/** Nuxt marks the channels as experimental, so every field is optional. */ +interface NuxtRenderPayload { + ssrContext?: { + error?: boolean; + payload?: { error?: { status?: unknown; statusCode?: unknown } }; + '~renderResponse'?: unknown; + /** The older name of `~renderResponse`. */ + _renderResponse?: unknown; + nuxt?: { $router?: { currentRoute?: { value?: { matched?: Array<{ path?: unknown }> } } } }; + }; +} + +const INTEGRATION_NAME = 'NuxtTracingChannel'; + +function isErrorPageRender({ ssrContext }: NuxtRenderPayload): boolean { + return ssrContext?.error === true; +} + +function startRenderSpan(payload: NuxtRenderPayload): Span | undefined { + // Without a request root span, for example with tracing off, return no span. A non-recording span would become + // active and hide the incoming trace from errors in the render. + if (!getActiveSpan()) { + return undefined; + } + + const name = isErrorPageRender(payload) ? 'renderErrorPage' : 'renderPage'; + + return startInactiveSpan({ + name, + attributes: { + [SENTRY_OP]: FUNCTION, + [SENTRY_ORIGIN]: 'auto.function.nuxt.render', + [CODE_FUNCTION_NAME]: name, + }, + }); +} + +function getMatchedRoute({ ssrContext }: NuxtRenderPayload): string | undefined { + const matched = ssrContext?.nuxt?.$router?.currentRoute?.value?.matched; + const path = matched?.[matched.length - 1]?.path; + return typeof path === 'string' ? path : undefined; +} + +/** After a redirect in a route middleware or a plugin, Nuxt rejects the render and catches the error itself. */ +function isSkippedRender(data: TracingChannelPayloadWithSpan): boolean { + return 'error' in data && !!(data.ssrContext?.['~renderResponse'] ?? data.ssrContext?._renderResponse); +} + +/** + * A component error does not reject the render. Nuxt keeps the error in the payload and throws it after the render. + * A 3xx or 4xx error is not a failure, as in `sentryCaptureErrorHook`. + */ +function isFailedPageRender(payload: NuxtRenderPayload): boolean { + const error = payload.ssrContext?.payload?.error; + if (!error || isErrorPageRender(payload)) { + return false; + } + + const statusCode = Number(error.status ?? error.statusCode); + return !(statusCode >= 300 && statusCode < 500); +} + +function setRenderResult(span: Span, data: TracingChannelPayloadWithSpan): void { + if (isSkippedRender(data)) { + // Undo the error state from `bindTracingChannelToSpan`. No route, because the router is at the redirect target. + span.setStatus({ code: SPAN_STATUS_OK }); + span.setAttribute(ERROR_TYPE, undefined); + return; + } + + // The Vue router resolves the route during the render, so it is only known now. + const route = getMatchedRoute(data); + if (route) { + span.setAttribute(HTTP_ROUTE, route); + } + + if (isFailedPageRender(data)) { + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); + } +} + +/** Makes spans from the `nuxt.*` tracing channels. Nuxt publishes nothing when the `nuxt` channel group is off. */ +export const nuxtTracingChannelIntegration = defineIntegration(() => ({ + name: INTEGRATION_NAME, + setupOnce() { + if (!diagnosticsTracingChannel) { + return; + } + + // The `http.server` span of the runtime SDK stays the request root, not a `nuxt.request` or `srvx.request` span. + // It also exists without these channels, and it already has the HTTP data and the incoming trace. + bindTracingChannelToSpan(diagnosticsTracingChannel('nuxt.render'), startRenderSpan, { + beforeSpanEnd: setRenderResult, + }); + }, +})); + +/** Adds the integration next to the defaults, so that an `integrations` function of the user can remove it. */ +export function withNuxtTracingChannelIntegration( + userIntegrations: Options['integrations'], +): (defaultIntegrations: Integration[]) => Integration[] { + return defaultIntegrations => { + const integrations = [...defaultIntegrations, nuxtTracingChannelIntegration()]; + + return typeof userIntegrations === 'function' + ? userIntegrations(integrations) + : [...integrations, ...(userIntegrations ?? [])]; + }; +} diff --git a/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts b/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts index 21df1f940fd8..9880a91d0a97 100644 --- a/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts +++ b/packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts @@ -5,6 +5,7 @@ import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata } from '@sentry/cor // A namespace import keeps a missing `withEnv` export a missing property instead of a module linking error. import * as cloudflareWorkers from 'cloudflare:workers'; import { getBuildAssetRequestFilters } from './buildAssetRequestFilters'; +import { withNuxtTracingChannelIntegration } from './nuxtTracingChannelIntegration'; type OptionsCallback = (env: unknown) => CloudflareOptions; type NitroDurableObjectClass = new (state: DurableObjectState, env: unknown) => object; @@ -30,7 +31,7 @@ export function wrapNitroCloudflareEntryWithSentry { @@ -71,16 +72,17 @@ export function wrapNitroDurableObjectWithSentry( }); } - return instrumentDurableObjectWithSentry(withNuxtSdkMetadata(optionsCallback), NitroDurableObjectWithEnv); + return instrumentDurableObjectWithSentry(withNuxtSdkOptions(optionsCallback), NitroDurableObjectWithEnv); } function runWithEnv(env: unknown, callback: () => unknown): unknown { return cloudflareWorkers.withEnv && env !== undefined ? cloudflareWorkers.withEnv(env, callback) : callback(); } -function withNuxtSdkMetadata(optionsCallback: OptionsCallback): OptionsCallback { +function withNuxtSdkOptions(optionsCallback: OptionsCallback): OptionsCallback { return env => { - const options = _INTERNAL_captureOptionsSetByUser({ ...optionsCallback(env) }); + const userOptions = _INTERNAL_captureOptionsSetByUser({ ...optionsCallback(env) }); + const options = { ...userOptions, integrations: withNuxtTracingChannelIntegration(userOptions.integrations) }; applySdkMetadata(options, 'nuxt', ['nuxt', 'cloudflare']); return options; }; diff --git a/packages/nuxt/src/server/sdk.ts b/packages/nuxt/src/server/sdk.ts index 5bc7e354a054..53acc72c3261 100644 --- a/packages/nuxt/src/server/sdk.ts +++ b/packages/nuxt/src/server/sdk.ts @@ -23,6 +23,7 @@ import { } from '../common/devMode'; import type { SentryNuxtServerOptions } from '../common/types'; import { getBuildAssetRequestFilters } from '../runtime/utils/buildAssetRequestFilters'; +import { withNuxtTracingChannelIntegration } from '../runtime/utils/nuxtTracingChannelIntegration'; /** * Initializes the server-side of the Nuxt SDK @@ -65,7 +66,7 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { const sentryOptions = { environment: options.environment ?? process.env.SENTRY_ENVIRONMENT ?? envFallback, ...userOptions, - integrations: withNuxtNitroIntegration(userOptions.integrations), + integrations: withNuxtIntegrations(userOptions.integrations), ignoreSpans: [ ...(options.ignoreSpans || []), ...getBuildAssetRequestFilters(getNuxtBuildAssetsPath()), @@ -91,26 +92,25 @@ export function init(options: SentryNuxtServerOptions): Client | undefined { /** * 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. + * Also adds `nuxtTracingChannelIntegration`. * * It wraps `integrations` and not `defaultIntegrations`, because only `initNode` resolves the defaults correctly * (it also reads `SENTRY_TRACES_SAMPLE_RATE`). */ -function withNuxtNitroIntegration( +function withNuxtIntegrations( 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, + const withTracingChannelIntegration = withNuxtTracingChannelIntegration(userIntegrations); + + return defaultIntegrations => + withTracingChannelIntegration( + 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 ?? [])]; - }; } /** diff --git a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts index 4a4bd3c725de..6f54ba40047c 100644 --- a/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts +++ b/packages/nuxt/test/runtime/plugins/sentry-cloudflare.server.test.ts @@ -1,6 +1,7 @@ import type { CloudflareOptions } from '@sentry/cloudflare'; import { serveTunnelIntegration } from '@sentry/cloudflare'; import { wrapRequestHandler } from '@sentry/cloudflare/request'; +import type { Integration } from '@sentry/core'; import { getTunnelPath, SDK_VERSION } from '@sentry/core'; import type { NitroApp } from 'nitropack'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -87,6 +88,23 @@ describe('sentryCloudflareNitroPlugin', () => { ); }); + it('adds the integration for the tracing channels of Nuxt to the integrations of the app', async () => { + let options: CloudflareOptions | undefined; + vi.mocked(wrapRequestHandler).mockImplementationOnce(async (wrapperOptions, callback) => { + options = wrapperOptions.options; + return callback(); + }); + + await handleRequest({ dsn: DSN, integrations: [serveTunnelIntegration()] }); + + const integrations = options?.integrations as (defaultIntegrations: Integration[]) => Integration[]; + expect(integrations([{ name: 'Fetch' }]).map(integration => integration.name)).toEqual([ + 'Fetch', + 'NuxtTracingChannel', + 'ServeTunnel', + ]); + }); + it('answers a managed tunnel request with the body Nitro read', async () => { const actual = await vi.importActual<{ wrapRequestHandler: typeof wrapRequestHandler }>( '@sentry/cloudflare/request', diff --git a/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts b/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts new file mode 100644 index 000000000000..b1f14acbce71 --- /dev/null +++ b/packages/nuxt/test/runtime/utils/nuxtTracingChannelIntegration.test.ts @@ -0,0 +1,322 @@ +/** @vitest-environment node */ +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { CODE_FUNCTION_NAME, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; +import { FUNCTION, HTTP_CLIENT, HTTP_SERVER } from '@sentry/conventions/op'; +import type { Client, Integration, StreamedSpanJSON } from '@sentry/core'; +import { createTransport, getActiveSpan, getCurrentScope, spanToJSON, startNewTrace, startSpan } from '@sentry/core'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { withNuxtTracingChannelIntegration } from '../../../src/runtime/utils/nuxtTracingChannelIntegration'; +import { init } from '../../../src/server'; + +type TraceAsync = (name: string, context: object, fn: () => Promise) => Promise; + +/** Nuxt's own `traceAsync`. It is not in the `exports` of `nuxt`, so the test imports the file by path. */ +async function importNuxtTraceAsync(): Promise { + const nuxtDir = dirname(createRequire(import.meta.url).resolve('nuxt/package.json')); + const tracing: { traceAsync: TraceAsync } = await import( + pathToFileURL(join(nuxtDir, 'dist/app/internal/tracing.js')).href + ); + return tracing.traceAsync; +} + +const RENDER_ORIGIN = 'auto.function.nuxt.render'; + +function renderSpanAttributes(name: string): Record { + return { [SENTRY_OP]: FUNCTION, [SENTRY_ORIGIN]: RENDER_ORIGIN, [CODE_FUNCTION_NAME]: name }; +} + +// All tests share one client, because the channel subscribers of an integration stay for the whole process. +describe('nuxtTracingChannelIntegration', () => { + let client: Client; + let traceAsync: TraceAsync; + const endedSpans: StreamedSpanJSON[] = []; + + /** Publishes a `nuxt.render` event inside an `http.server` root span. Returns the ended spans of that request. */ + async function render( + payload: object, + renderToString: () => Promise = () => Promise.resolve({ html: '
' }), + { rejects = false }: { rejects?: boolean } = {}, + ): Promise { + const traceId = await startNewTrace(() => + startSpan({ name: 'GET', op: HTTP_SERVER }, async rootSpan => { + const rendered = traceAsync('nuxt.render', payload, renderToString); + await (rejects ? rendered.catch(() => undefined) : rendered); + return spanToJSON(rootSpan).trace_id; + }), + ); + + return endedSpans.filter(span => span.trace_id === traceId); + } + + function getParent(span: StreamedSpanJSON | undefined, spans: StreamedSpanJSON[]): StreamedSpanJSON | undefined { + return spans.find(candidate => candidate.span_id === span?.parent_span_id); + } + + beforeAll(async () => { + traceAsync = await importNuxtTraceAsync(); + + 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))); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + afterAll(async () => { + await client.close(); + getCurrentScope().setClient(undefined); + }); + + describe('nuxt.render', () => { + it('creates a `renderPage` span as a child of the request root span', async () => { + const spans = await render({ ssrContext: { error: false, url: '/test-param/1234' }, streaming: false }); + + const renderSpans = spans.filter(span => span.attributes[SENTRY_OP] === FUNCTION); + + expect(renderSpans).toHaveLength(1); + expect(renderSpans[0]?.name).toBe('renderPage'); + expect(renderSpans[0]?.attributes).toEqual(renderSpanAttributes('renderPage')); + expect(renderSpans[0]?.status).toBe('ok'); + expect(getParent(renderSpans[0], spans)?.attributes[SENTRY_OP]).toBe(HTTP_SERVER); + }); + + it('names the span `renderErrorPage` for the render of the error page', async () => { + const spans = await render({ ssrContext: { error: true, url: '/ssr-error' }, streaming: false }); + + const renderSpans = spans.filter(span => span.attributes[SENTRY_OP] === FUNCTION); + + expect(renderSpans).toHaveLength(1); + expect(renderSpans[0]?.name).toBe('renderErrorPage'); + expect(renderSpans[0]?.attributes).toEqual(renderSpanAttributes('renderErrorPage')); + }); + + it('adds the route that the Vue router matched during the render', async () => { + const ssrContext: Record = { error: false, url: '/users/42/posts/7?include=comments' }; + + // Nuxt sets `ssrContext.nuxt` during the render. + const spans = await render({ ssrContext, streaming: false }, async () => { + ssrContext.nuxt = { + $router: { + currentRoute: { value: { matched: [{ path: '/users/:id()' }, { path: '/users/:id()/posts/:postId()' }] } }, + }, + }; + }); + + const renderSpan = spans.find(span => span.name === 'renderPage'); + + expect(renderSpan?.attributes).toEqual({ + ...renderSpanAttributes('renderPage'), + [HTTP_ROUTE]: '/users/:id()/posts/:postId()', + }); + }); + + it.each([ + { description: 'no `ssrContext`', payload: {} }, + { description: 'a `ssrContext` that is no object', payload: { ssrContext: 'ssr-context' } }, + { description: 'no Nuxt app', payload: { ssrContext: { error: false, nuxt: undefined } } }, + { description: 'no router', payload: { ssrContext: { error: false, nuxt: {} } } }, + { + description: 'a route that matches no page', + payload: { ssrContext: { error: false, nuxt: { $router: { currentRoute: { value: { matched: [] } } } } } }, + }, + { + description: 'a matched route without a path', + payload: { ssrContext: { error: false, nuxt: { $router: { currentRoute: { value: { matched: [{}] } } } } } }, + }, + ])('creates a `renderPage` span without a route for a payload with $description', async ({ payload }) => { + const spans = await render(payload); + + const renderSpans = spans.filter(span => span.attributes[SENTRY_OP] === FUNCTION); + + expect(renderSpans).toHaveLength(1); + expect(renderSpans[0]?.attributes).toEqual(renderSpanAttributes('renderPage')); + }); + + it('makes a span that starts during the render a child of the render span', async () => { + const spans = await render({ ssrContext: { error: false }, streaming: false }, () => + startSpan({ name: 'GET https://api.example.com/users/42', op: HTTP_CLIENT }, () => Promise.resolve()), + ); + + const fetchSpan = spans.find(span => span.attributes[SENTRY_OP] === HTTP_CLIENT); + + expect(fetchSpan).toBeDefined(); + expect(getParent(fetchSpan, spans)?.name).toBe('renderPage'); + }); + + it('ends the span when the render settles, not when the render returns its promise', async () => { + const activeSpansAfterAwait: Array> = []; + + await render({ ssrContext: { error: false }, streaming: false }, async () => { + await new Promise(resolve => setTimeout(resolve, 5)); + const { name, end_timestamp } = spanToJSON(getActiveSpan()!); + activeSpansAfterAwait.push({ name, end_timestamp }); + }); + + expect(activeSpansAfterAwait).toEqual([{ name: 'renderPage', end_timestamp: undefined }]); + }); + + it('sets the error status on the span of a render that rejects', async () => { + const spans = await render( + { ssrContext: { error: false }, streaming: false }, + () => Promise.reject(new TypeError('Cannot read properties of undefined (reading "title")')), + { rejects: true }, + ); + + expect(spans.find(span => span.name === 'renderPage')?.status).toBe('error'); + }); + + it('captures no error for a render that rejects, because the Nitro error hook captures it', async () => { + const captureException = vi.spyOn(client, 'captureException'); + + await render( + { ssrContext: { error: false }, streaming: false }, + () => Promise.reject(new TypeError('Cannot read properties of undefined (reading "title")')), + { rejects: true }, + ); + + expect(captureException).not.toHaveBeenCalled(); + }); + + it('sets the error status when a component fails and Nuxt keeps the error in the payload', async () => { + const ssrContext: Record = { error: false, payload: {} }; + + const spans = await render({ ssrContext, streaming: false }, async () => { + ssrContext.payload = { error: { statusCode: 500, message: 'Nuxt 4 SSR error' } }; + }); + + expect(spans.find(span => span.name === 'renderPage')?.status).toBe('error'); + }); + + it.each([ + { description: 'an error without a status code', error: { message: 'Nuxt 4 SSR error' } }, + { description: 'a 503 error with the deprecated `statusCode`', error: { statusCode: 503 } }, + { description: 'a 299 status', error: { status: 299 } }, + { description: 'a 500 status', error: { status: 500 } }, + ])('sets the error status when the payload has $description', async ({ error }) => { + const spans = await render({ ssrContext: { error: false, payload: { error } }, streaming: false }); + + expect(spans.find(span => span.name === 'renderPage')?.status).toBe('error'); + }); + + // `sentryCaptureErrorHook` does not report these errors either. + it.each([ + { description: 'a 404 status', error: { status: 404, statusText: 'Page not found: /products/unknown' } }, + { description: 'a 404 error with the deprecated `statusCode`', error: { statusCode: 404 } }, + { description: 'a 300 status', error: { status: 300 } }, + { description: 'a 499 status', error: { status: 499 } }, + ])('keeps the ok status when the payload has $description', async ({ error }) => { + const spans = await render({ ssrContext: { error: false, payload: { error } }, streaming: false }); + + expect(spans.find(span => span.name === 'renderPage')?.status).toBe('ok'); + }); + + it('keeps the ok status and adds no route for a render that Nuxt skips after a redirect in a route middleware', async () => { + const ssrContext = { + error: false, + '~renderResponse': { statusCode: 302, headers: { location: '/login' } }, + // The router is already at the target of the redirect. + nuxt: { $router: { currentRoute: { value: { matched: [{ path: '/login' }] } } } }, + }; + + // Nuxt rejects the render with this error and catches it. + const spans = await render({ ssrContext, streaming: false }, () => Promise.reject(new Error('skipping render')), { + rejects: true, + }); + + const renderSpan = spans.find(span => span.name === 'renderPage'); + + expect(renderSpan?.status).toBe('ok'); + expect(renderSpan?.attributes).toEqual(renderSpanAttributes('renderPage')); + }); + + it('adds the route of a page that redirects while it renders', async () => { + const ssrContext = { + error: false, + '~renderResponse': { statusCode: 302, headers: { location: '/login' } }, + nuxt: { $router: { currentRoute: { value: { matched: [{ path: '/account' }] } } } }, + }; + + const spans = await render({ ssrContext, streaming: false }); + + const renderSpan = spans.find(span => span.name === 'renderPage'); + + expect(renderSpan?.status).toBe('ok'); + expect(renderSpan?.attributes).toEqual({ ...renderSpanAttributes('renderPage'), [HTTP_ROUTE]: '/account' }); + }); + + it('keeps the ok status for the render of the error page, whose payload has the error', async () => { + const spans = await render({ + ssrContext: { error: true, payload: { error: { statusCode: 500, message: 'Nuxt 4 SSR error' } } }, + streaming: false, + }); + + expect(spans.find(span => span.name === 'renderErrorPage')?.status).toBe('ok'); + }); + + it('lets the error of a failed render reach Nuxt', async () => { + const renderError = new TypeError('Cannot read properties of undefined (reading "title")'); + + const rendered = startSpan({ name: 'GET', op: HTTP_SERVER }, () => + traceAsync('nuxt.render', { ssrContext: { error: false } }, () => Promise.reject(renderError)), + ); + + await expect(rendered).rejects.toBe(renderError); + }); + + it('creates no span for a render outside a request root span', async () => { + const endedSpanCount = endedSpans.length; + + await traceAsync('nuxt.render', { ssrContext: { error: false }, streaming: false }, () => Promise.resolve()); + + expect(endedSpans).toHaveLength(endedSpanCount); + }); + + // An active non-recording span would hide the incoming trace from errors in the render. + it('sets no active span for a render outside a request root span', async () => { + const activeSpans: unknown[] = []; + + await traceAsync('nuxt.render', { ssrContext: { error: false }, streaming: false }, async () => { + activeSpans.push(getActiveSpan()); + }); + + expect(activeSpans).toEqual([undefined]); + }); + }); +}); + +describe('withNuxtTracingChannelIntegration', () => { + const httpIntegration = { name: 'Http' }; + const appIntegration = { name: 'AppIntegration' }; + + it('adds the integration after the default integrations', () => { + const integrations = withNuxtTracingChannelIntegration(undefined)([httpIntegration]); + + expect(integrations.map(integration => integration.name)).toEqual(['Http', 'NuxtTracingChannel']); + }); + + it('keeps the integrations of a user array', () => { + const integrations = withNuxtTracingChannelIntegration([appIntegration])([httpIntegration]); + + expect(integrations.map(integration => integration.name)).toEqual(['Http', 'NuxtTracingChannel', 'AppIntegration']); + }); + + it('passes the integration to a user function, which can remove it', () => { + const removeNuxtIntegration = (defaults: Integration[]): Integration[] => + defaults.filter(integration => integration.name !== 'NuxtTracingChannel'); + + const integrations = withNuxtTracingChannelIntegration(removeNuxtIntegration)([httpIntegration]); + + expect(integrations).toEqual([httpIntegration]); + }); +}); diff --git a/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts b/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts index e1a01b993985..f077912ca59b 100644 --- a/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts +++ b/packages/nuxt/test/runtime/utils/wrapCloudflareEntry.test.ts @@ -2,6 +2,7 @@ import type { ExportedHandler } from '@cloudflare/workers-types'; import { URL_PATH } from '@sentry/conventions/attributes'; import { HTTP_SERVER } from '@sentry/conventions/op'; +import type { Integration } from '@sentry/core'; import { SDK_VERSION } from '@sentry/core'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { @@ -36,6 +37,8 @@ vi.mock('@sentry/cloudflare', () => ({ }), })); +type ResolveIntegrations = (defaultIntegrations: Integration[]) => Integration[]; + type WrappedHandler = { optionsCallback: (env: unknown) => unknown; handler: Record unknown>; @@ -80,10 +83,26 @@ describe('wrapNitroCloudflareEntryWithSentry', () => { ], }, }, + integrations: expect.any(Function), ignoreSpans: [], }); }); + it('adds the integration for the tracing channels of Nuxt to the integrations of the app', () => { + const wrapped = wrapNitroCloudflareEntryWithSentry( + () => ({ integrations: [{ name: 'AppIntegration' }] }), + {}, + ) as unknown as WrappedHandler; + + const { integrations } = wrapped.optionsCallback({}) as { integrations: ResolveIntegrations }; + + expect(integrations([{ name: 'Fetch' }]).map(integration => integration.name)).toEqual([ + 'Fetch', + 'NuxtTracingChannel', + 'AppIntegration', + ]); + }); + it('ignores the server spans of requests to the build output after the `ignoreSpans` of the app', () => { const healthCheckFilter = { attributes: { [URL_PATH]: '/health' } }; const wrapped = wrapNitroCloudflareEntryWithSentry( @@ -158,8 +177,23 @@ describe('wrapNitroDurableObjectWithSentry', () => { ], }, }, + integrations: expect.any(Function), }); }); + + it('adds the integration for the tracing channels of Nuxt', () => { + const { optionsCallback } = wrapNitroDurableObjectWithSentry( + () => ({}), + NitroDurableObject, + ) as unknown as WrappedDurableObject; + + const { integrations } = optionsCallback({}) as { integrations: ResolveIntegrations }; + + expect(integrations([{ name: 'Fetch' }]).map(integration => integration.name)).toEqual([ + 'Fetch', + 'NuxtTracingChannel', + ]); + }); }); describe('without `withEnv` in `cloudflare:workers`', () => { diff --git a/packages/nuxt/test/server/sdk.test.ts b/packages/nuxt/test/server/sdk.test.ts index 5978d3f63597..1c20aed88088 100644 --- a/packages/nuxt/test/server/sdk.test.ts +++ b/packages/nuxt/test/server/sdk.test.ts @@ -221,6 +221,24 @@ describe('Nuxt Server SDK', () => { }); }); + describe('Nuxt tracing channel integration', () => { + it('adds the integration to the default integrations', () => { + const client = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' }); + + expect(client?.getIntegrationByName('NuxtTracingChannel')).toBeDefined(); + }); + + it('lets a user `integrations` function remove the integration', () => { + const client = init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: defaults => defaults.filter(integration => integration.name !== 'NuxtTracingChannel'), + }); + + expect(client).toBeDefined(); + expect(client?.getIntegrationByName('NuxtTracingChannel')).toBeUndefined(); + }); + }); + describe('environment option', () => { const originalEnv = process.env.SENTRY_ENVIRONMENT;