Skip to content
Open
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 @@ -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;
Expand Down
116 changes: 116 additions & 0 deletions packages/nuxt/src/runtime/utils/nuxtTracingChannelIntegration.ts
Original file line number Diff line number Diff line change
@@ -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<NuxtRenderPayload>): 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<NuxtRenderPayload>): 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<NuxtRenderPayload>('nuxt.render'), startRenderSpan, {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: with experimental.ssrStreaming on, renderStreamedResponse() resolves after the first chunk, so renderPage only covers the shell and misses later errors. Fine to handle in a follow-up, maybe just skip streaming: true for now?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe verify e2e

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 ?? [])];
};
}
10 changes: 6 additions & 4 deletions packages/nuxt/src/runtime/utils/wrapCloudflareEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -30,7 +31,7 @@ export function wrapNitroCloudflareEntryWithSentry<Handler extends ExportedHandl
]),
) as Handler;

const optionsCallbackWithMetadata = withNuxtSdkMetadata(optionsCallback);
const optionsCallbackWithMetadata = withNuxtSdkOptions(optionsCallback);
// Nitro sends a request for a build file that the Cloudflare assets do not have to `env.ASSETS` before the Nitro app
// runs, but `withSentry` sees the request.
return withSentry(env => {
Expand Down Expand Up @@ -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;
};
Expand Down
24 changes: 12 additions & 12 deletions packages/nuxt/src/server/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()),
Expand All @@ -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<SentryNuxtServerOptions['integrations']> {
// 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 ?? [])];
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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',
Expand Down
Loading
Loading