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
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { useRoute } from '#imports';

// The id makes the error of each request distinct, so that a test can count the events of its own request.
throw new Error(`Nuxt 4 SSR error ${useRoute().query.id}`);
</script>

<template>
<p>This page fails while it renders.</p>
</template>
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { CACHE_HIT, URL_PATH } from '@sentry/conventions/attributes';
import { CACHE_GET, CACHE_PUT } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';

test.skip(isViteServer, NITRO_ONLY);
Expand All @@ -18,6 +20,15 @@ test.describe('Cache Instrumentation', () => {
return spans.filter(span => span.attributes['sentry.origin']?.value === 'auto.cache.nuxt');
}

/** Every span of the request's trace, whatever created it, so that a second span for one cache access shows up. */
function collectRequestSpans() {
return collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes[URL_PATH]?.value === '/api/cache-test',
span => getSpanOp(span) === CACHE_GET,
);
}

test('instruments cachedFunction and cachedEventHandler calls and creates spans with correct attributes', async ({
request,
}) => {
Expand Down Expand Up @@ -151,4 +162,37 @@ test.describe('Cache Instrumentation', () => {
// We should have at least one cache hit (second calls to getCachedUser and getCachedData)
expect(cacheHitSpans.length).toBeGreaterThanOrEqual(1);
});

test('creates exactly one span for each cache read and write', async ({ request }) => {
// Unique keys, so that the first call of each cached function is a cache miss.
const uniqueKey = `count-${Date.now()}`;
const spansPromise = collectRequestSpans();

await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`);

const spans = await spansPromise;
const readSpans = spans.filter(span => getSpanOp(span) === CACHE_GET);
const writeSpans = spans.filter(span => getSpanOp(span) === CACHE_PUT);
const cacheMissSpans = readSpans.filter(span => span.attributes[CACHE_HIT]?.value === false);

// 3x getCachedUser, 2x getCachedData, 1x cachedHandler.
expect(readSpans).toHaveLength(6);
// One write for each cache miss. An earlier test can have filled the cache of the handler, so the number of
// misses is not fixed.
expect(writeSpans).toHaveLength(cacheMissSpans.length);
});

test('makes each cache span a child of the request root span', async ({ request }) => {
const uniqueKey = `parent-${Date.now()}`;
const spansPromise = collectRequestSpans();

await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`);

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const cacheSpans = spans.filter(span => getSpanOp(span) === CACHE_GET || getSpanOp(span) === CACHE_PUT);
const parentSpanIds = new Set(cacheSpans.map(span => span.parent_span_id));

expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id]));
});
});
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { URL_PATH } from '@sentry/conventions/attributes';
import { DB_QUERY } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';
Expand All @@ -12,15 +14,19 @@ const DB_ERROR_MECHANISM =
? { handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 }
: { handled: false, type: 'auto.db.nuxt' };

async function collectDbSpans() {
const spans = await collectStreamedSpansUntilSegment(
function collectRequestSpans() {
return collectStreamedSpansUntilSegment(
'nuxt-4',
span => span.attributes['url.path']?.value === '/api/db-test',
span => getSpanOp(span) === 'db.query',
span => span.attributes[URL_PATH]?.value === '/api/db-test',
span => getSpanOp(span) === DB_QUERY,
);
const rootSpan = spans.find(span => span.is_segment && span.attributes['url.path']?.value === '/api/db-test');
}

return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === 'db.query');
async function collectDbSpans() {
const spans = await collectRequestSpans();
const rootSpan = spans.find(span => span.is_segment && span.attributes[URL_PATH]?.value === '/api/db-test');

return spans.filter(span => span.trace_id === rootSpan?.trace_id && getSpanOp(span) === DB_QUERY);
}

test.describe('database integration', () => {
Expand Down Expand Up @@ -210,4 +216,17 @@ test.describe('database integration', () => {
expect(dbSpans.length).toBeGreaterThanOrEqual(1);
expect(dbSpans.every(span => !span.is_segment)).toBe(true);
});

test('makes each db.query span a child of the request root span', async ({ request }) => {
const spansPromise = collectRequestSpans();

await request.get('/api/db-test?method=prepare-get');

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const dbSpans = spans.filter(span => getSpanOp(span) === DB_QUERY);
const parentSpanIds = new Set(dbSpans.map(span => span.parent_span_id));

expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id]));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { HTTP_RESPONSE_STATUS_CODE, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForEnvelopeItem, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';

type EnvelopeItem = Parameters<Parameters<typeof waitForEnvelopeItem>[1]>[0];
type SentryErrorEvent = Awaited<ReturnType<typeof waitForError>>;

const SSR_ERROR_PATH = '/ssr-error';
const SSR_ERROR_MESSAGE = 'Nuxt 4 SSR error';
// A page that every server API renders. The test requests it after the failing page, so its root span arrives
// after every event of the failing request.
const BARRIER_PATH = '/test-param/ssr-error-barrier';

function getErrorEvents([header, payload]: EnvelopeItem): SentryErrorEvent[] {
return header.type === 'event' ? [payload as SentryErrorEvent] : [];
}

function getStreamedSpans([header, payload]: EnvelopeItem): SerializedStreamedSpan[] {
return header.type === 'span' ? (payload as { items: SerializedStreamedSpan[] }).items : [];
}

function hasErrorMessage(errorEvent: SentryErrorEvent, message: string): boolean {
return !!errorEvent.exception?.values?.some(value => value.value?.startsWith(message));
}

function waitForRootSpan() {
return waitForStreamedSpan(
'nuxt-4',
span => !!span.is_segment && span.attributes[URL_PATH]?.value === SSR_ERROR_PATH,
);
}

test.describe('page that fails during SSR', () => {
test('captures the error exactly once', async ({ request }) => {
test.fail(isViteServer, 'Known bug: the Vite server has no error hook, so the SDK captures no SSR error');

const requestId = `${Date.now()}`;
// One listener for events and spans, so it has every event that the proxy received before the barrier span.
const receivedErrors: SentryErrorEvent[] = [];
const barrierPromise = waitForEnvelopeItem('nuxt-4', envelopeItem => {
receivedErrors.push(...getErrorEvents(envelopeItem));
return getStreamedSpans(envelopeItem).some(
span => span.is_segment && span.attributes[URL_PATH]?.value === BARRIER_PATH,
);
});

await request.get(`${SSR_ERROR_PATH}?id=${requestId}`);
await request.get(BARRIER_PATH);
await barrierPromise;

const errorsOfRequest = receivedErrors.filter(errorEvent =>
hasErrorMessage(errorEvent, `${SSR_ERROR_MESSAGE} ${requestId}`),
);

expect(errorsOfRequest).toHaveLength(1);
});

test('reports the error through the Nitro error hook', async ({ request }) => {
test.skip(isViteServer, NITRO_ONLY);

const errorPromise = waitForError('nuxt-4', errorEvent => hasErrorMessage(errorEvent, SSR_ERROR_MESSAGE));

await request.get(SSR_ERROR_PATH);

const errorEvent = await errorPromise;

expect(errorEvent.transaction).toBe(`GET ${SSR_ERROR_PATH}`);
expect(errorEvent.exception?.values?.map(value => value.mechanism)).toEqual([
{ handled: true, type: 'chained', exception_id: 1, parent_id: 0, source: 'cause' },
{ handled: false, type: 'auto.function.nuxt.nitro', exception_id: 0 },
]);
});

test('marks the root span as errored', async ({ request }) => {
const rootSpanPromise = waitForRootSpan();

await request.get(SSR_ERROR_PATH);

const rootSpan = await rootSpanPromise;

expect(rootSpan.status).toBe('error');
expect(rootSpan.attributes[HTTP_RESPONSE_STATUS_CODE]).toEqual({ type: 'integer', value: 500 });
});

test('names the root span after the page route', async ({ request }) => {
test.fail(
true,
'Known bug: the root span of a failed render gets no page route. On Nitro, it takes the name of the internal `/__nuxt_error` request. On the Vite server, the name is `GET`',
);

const rootSpanPromise = waitForRootSpan();

await request.get(SSR_ERROR_PATH);

const rootSpan = await rootSpanPromise;

expect(rootSpan.name).toBe(`GET ${SSR_ERROR_PATH}`);
});
});
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MIDDLEWARE as MIDDLEWARE_OP } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment, getSpanOp, waitForError } from '@sentry-internal/test-utils';
import { IMPORT_SURFACES } from './importSurfaces';
Expand Down Expand Up @@ -346,3 +347,14 @@ test.describe('Server Middleware Instrumentation (#imports hooks)', () => {
expect(onRequest0Span?.status).toBe('ok');
});
});

test('creates exactly one span for each server middleware handler of a request', async ({ request }) => {
const spansPromise = collectRequestSpans();

await request.get('/api/middleware-test');

// No filter on the middleware name, so a `middleware` span from any other source fails the count.
const middlewareSpans = (await spansPromise).filter(span => getSpanOp(span) === MIDDLEWARE_OP);

expect(middlewareSpans).toHaveLength(MIDDLEWARE['#imports'].spanCount + MIDDLEWARE['nuxt/server'].spanCount);
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { URL_PATH } from '@sentry/conventions/attributes';
import { CACHE_GET, CACHE_PUT, CACHE_REMOVE } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';
import type { SerializedStreamedSpan } from '@sentry-internal/test-utils';
import { isViteServer, NITRO_ONLY } from './isViteServer';

test.skip(isViteServer, NITRO_ONLY);
Expand All @@ -17,6 +20,14 @@ async function collectStorageSpans(route: string) {
);
}

const STORAGE_OPS: ReadonlyArray<string | undefined> = [CACHE_GET, CACHE_PUT, CACHE_REMOVE];
const isStorageSpan = (span: SerializedStreamedSpan) => STORAGE_OPS.includes(getSpanOp(span));

/** Every span of the request's trace, whatever created it, so that a second span for one storage call shows up. */
function collectRequestSpans(route: string) {
return collectStreamedSpansUntilSegment('nuxt-4', span => span.attributes[URL_PATH]?.value === route, isStorageSpan);
}

test.describe('Storage Instrumentation', () => {
const prefixKey = (key: string) => `test-storage:${key}`;
const SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';
Expand Down Expand Up @@ -158,4 +169,30 @@ test.describe('Storage Instrumentation', () => {
expect(span.status).toBe('ok');
});
});

test('creates exactly one span for each storage driver call', async ({ request }) => {
const spansPromise = collectRequestSpans('/api/storage-test');

await request.get('/api/storage-test');

const spanOps = (await spansPromise).map(getSpanOp);

// `/api/storage-test` writes 4 items, reads with hasItem, getItem, getItemRaw and 2x getKeys, and removes twice
// (removeItem, clear). Each `getKeys` call is 2 driver calls, because unstorage also asks the driver of the root mount.
expect(spanOps.filter(op => op === CACHE_PUT)).toHaveLength(4);
expect(spanOps.filter(op => op === CACHE_GET)).toHaveLength(7);
expect(spanOps.filter(op => op === CACHE_REMOVE)).toHaveLength(2);
});

test('makes each storage span a child of the request root span', async ({ request }) => {
const spansPromise = collectRequestSpans('/api/storage-test');

await request.get('/api/storage-test');

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const parentSpanIds = new Set(spans.filter(isStorageSpan).map(span => span.parent_span_id));

expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id]));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { useRoute } from '#imports';

// The id makes the error of each request distinct, so that a test can count the events of its own request.
throw new Error(`Nuxt 5 SSR error ${useRoute().query.id}`);
</script>

<template>
<p>This page fails while it renders.</p>
</template>
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { CACHE_HIT, URL_PATH } from '@sentry/conventions/attributes';
import { CACHE_GET, CACHE_PUT } from '@sentry/conventions/op';
import { expect, test } from '@playwright/test';
import { collectStreamedSpansUntilSegment } from '@sentry-internal/test-utils';
import { collectStreamedSpansUntilSegment, getSpanOp } from '@sentry-internal/test-utils';

// Nitro v3 only routes cached functions and handlers through KV storage with the `kv` cache driver,
// so the default (`memory`) driver is traced through ocache's storage instead.
Expand Down Expand Up @@ -27,6 +29,15 @@ test.describe('Cache Instrumentation', () => {
);
}

/** Every span of the request's trace, whatever created it, so that a second span for one cache access shows up. */
function collectRequestSpans() {
return collectStreamedSpansUntilSegment(
'nuxt-5',
span => span.attributes[URL_PATH]?.value === '/api/cache-test',
span => getSpanOp(span) === CACHE_GET,
);
}

test('instruments cachedFunction and cachedEventHandler calls and creates spans with correct attributes', async ({
request,
}) => {
Expand Down Expand Up @@ -160,4 +171,37 @@ test.describe('Cache Instrumentation', () => {
// We should have at least one cache hit (second calls to getCachedUser and getCachedData)
expect(cacheHitSpans.length).toBeGreaterThanOrEqual(1);
});

test('creates exactly one span for each cache read and write', async ({ request }) => {
// Unique keys, so that the first call of each cached function is a cache miss.
const uniqueKey = `count-${Date.now()}`;
const spansPromise = collectRequestSpans();

await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`);

const spans = await spansPromise;
const readSpans = spans.filter(span => getSpanOp(span) === CACHE_GET);
const writeSpans = spans.filter(span => getSpanOp(span) === CACHE_PUT);
const cacheMissSpans = readSpans.filter(span => span.attributes[CACHE_HIT]?.value === false);

// 3x getCachedUser, 2x getCachedData, 1x cachedHandler.
expect(readSpans).toHaveLength(6);
// One write for each cache miss. An earlier test can have filled the cache of the handler, so the number of
// misses is not fixed.
expect(writeSpans).toHaveLength(cacheMissSpans.length);
});

test('makes each cache span a child of the request root span', async ({ request }) => {
const uniqueKey = `parent-${Date.now()}`;
const spansPromise = collectRequestSpans();

await request.get(`/api/cache-test?user=${uniqueKey}&data=${uniqueKey}`);

const spans = await spansPromise;
const rootSpan = spans.find(span => span.is_segment);
const cacheSpans = spans.filter(span => getSpanOp(span) === CACHE_GET || getSpanOp(span) === CACHE_PUT);
const parentSpanIds = new Set(cacheSpans.map(span => span.parent_span_id));

expect(parentSpanIds).toEqual(new Set([rootSpan?.span_id]));
});
});
Loading
Loading