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
32 changes: 30 additions & 2 deletions packages/nuxt/src/server/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()),
Expand All @@ -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<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,
);

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.
Expand Down
69 changes: 69 additions & 0 deletions packages/nuxt/test/server/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
136 changes: 136 additions & 0 deletions packages/nuxt/test/server/tracingChannels.test.ts
Original file line number Diff line number Diff line change
@@ -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<Storage, 'mount' | 'setItem' | 'getItem' | 'removeItem'>;

/**
* 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<TModule>(specifier: string): Promise<TModule> {
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();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand All @@ -107,6 +107,10 @@ function setupH3TracingChannels(): void {
bindTracingChannelToSpan(
diagnosticsChannel.tracingChannel<H3TracingRequestEvent>('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
Expand Down
11 changes: 9 additions & 2 deletions packages/server-utils/src/integrations/nitro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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();
Expand Down
Loading
Loading