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 @@ -39,9 +39,7 @@ test('Sends a server function transaction with auto-instrumentation', async ({ p
);
});

test('Sends a server function transaction for a nested server function only if it is manually instrumented', async ({
page,
}) => {
test('Sends a server function transaction for a nested server function', async ({ page }) => {
const transactionEventPromise = waitForTransaction('tanstackstart-react-static', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
Expand Down Expand Up @@ -90,19 +88,27 @@ test('Sends a server function transaction for a nested server function only if i
]),
);

// Verify that globalFunctionMiddleware and testNestedLog are sibling spans under the root
const functionMiddlewareSpan = transactionEvent?.spans?.find(
(span: { description?: string; origin?: string }) =>
span.description === 'globalFunctionMiddleware' && span.origin === 'auto.middleware.tanstackstart',
);
const nestedSpan = transactionEvent?.spans?.find(
(span: { description?: string; origin?: string }) =>
span.description === 'testNestedLog' && span.origin === 'manual',
const outerSpan = transactionEvent?.spans?.find(span => span.description === 'GET /_serverFn/testNestedLog');
const manualSpan = transactionEvent?.spans?.find(
span => span.description === 'testNestedLog' && span.origin === 'manual',
);

expect(functionMiddlewareSpan).toBeDefined();
expect(nestedSpan).toBeDefined();
expect(manualSpan?.parent_span_id).toBe(outerSpan?.span_id);

// Both spans should be siblings under the same parent (root transaction)
expect(nestedSpan?.parent_span_id).toBe(functionMiddlewareSpan?.parent_span_id);
// The server function called inside the manual span gets its own span
expect(transactionEvent?.spans).toEqual(
expect.arrayContaining([
expect.objectContaining({
description: 'GET /_serverFn/testLog',
origin: 'auto.function.tanstackstart.server',
parent_span_id: manualSpan?.span_id,
status: 'ok',
}),
expect.objectContaining({
description: 'globalFunctionMiddleware',
origin: 'auto.middleware.tanstackstart',
parent_span_id: outerSpan?.span_id,
}),
]),
);
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
import { SENTRY_DESCRIPTION, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';

function isServerFnSegment(span: Parameters<typeof getSpanOp>[0]): boolean {
return (
Expand Down Expand Up @@ -44,20 +46,17 @@ test('Sends a server function span with auto-instrumentation', async ({ page })
);
});

test('Sends a server function span for a nested server function only if it is manually instrumented', async ({
page,
}) => {
test('Sends a server function span for a nested server function', async ({ page }) => {
const isAutoSpan = (span: { name?: string; attributes: Record<string, { value?: unknown }> }, name: string) =>
span.name === name && span.attributes[SENTRY_ORIGIN]?.value === 'auto.function.tanstackstart.server';

const spansPromise = collectStreamedSpans(
'tanstackstart-react',
spans =>
spans.some(isServerFnSegment) &&
spans.some(
span =>
span.name === 'testNestedLog' &&
span.attributes['sentry.origin']?.value === 'auto.function.tanstackstart.server',
) &&
spans.some(span => span.name === 'testNestedLog') &&
spans.some(span => span.name === 'globalFunctionMiddleware'),
spans.some(span => isAutoSpan(span, 'testNestedLog')) &&
spans.some(span => isAutoSpan(span, 'testLog')) &&
spans.some(span => span.name === 'testNestedLog' && span.attributes[SENTRY_ORIGIN]?.value === 'manual'),
);

await page.goto('/test-serverFn');
Expand All @@ -68,43 +67,41 @@ test('Sends a server function span for a nested server function only if it is ma

const spans = await spansPromise;

expect(spans).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'testNestedLog',
status: 'ok',
attributes: expect.objectContaining({
'sentry.op': { type: 'string', value: 'function' },
'sentry.origin': { type: 'string', value: 'auto.function.tanstackstart.server' },
'sentry.description': { type: 'string', value: 'GET /_serverFn/testNestedLog' },
'tanstackstart.function.filename': { type: 'string', value: 'src/routes/test-serverFn.tsx' },
}),
}),
]),
const outerSpan = spans.find(span => isAutoSpan(span, 'testNestedLog'));
const manualSpan = spans.find(
span => span.name === 'testNestedLog' && span.attributes[SENTRY_ORIGIN]?.value === 'manual',
);
const nestedSpan = spans.find(span => isAutoSpan(span, 'testLog'));

expect(outerSpan).toMatchObject({
name: 'testNestedLog',
status: 'ok',
attributes: expect.objectContaining({
[SENTRY_OP]: { type: 'string', value: FUNCTION },
[SENTRY_DESCRIPTION]: { type: 'string', value: 'GET /_serverFn/testNestedLog' },
'tanstackstart.function.filename': { type: 'string', value: 'src/routes/test-serverFn.tsx' },
}),
});
expect(manualSpan).toMatchObject({ status: 'ok', parent_span_id: outerSpan?.span_id });
expect(nestedSpan).toMatchObject({
name: 'testLog',
status: 'ok',
parent_span_id: manualSpan?.span_id,
attributes: expect.objectContaining({
[SENTRY_OP]: { type: 'string', value: FUNCTION },
[SENTRY_DESCRIPTION]: { type: 'string', value: 'GET /_serverFn/testLog' },
}),
});

expect(spans).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'testNestedLog',
status: 'ok',
name: 'globalFunctionMiddleware',
parent_span_id: outerSpan?.span_id,
attributes: expect.objectContaining({
'sentry.origin': { type: 'string', value: 'manual' },
[SENTRY_ORIGIN]: { type: 'string', value: 'auto.middleware.tanstackstart' },
}),
}),
]),
);

const functionMiddlewareSpan = spans.find(
span =>
span.name === 'globalFunctionMiddleware' &&
span.attributes['sentry.origin']?.value === 'auto.middleware.tanstackstart',
);
const nestedSpan = spans.find(
span => span.name === 'testNestedLog' && span.attributes['sentry.origin']?.value === 'manual',
);

expect(functionMiddlewareSpan).toBeDefined();
expect(nestedSpan).toBeDefined();
expect(nestedSpan?.parent_span_id).toBe(functionMiddlewareSpan?.parent_span_id);
});
73 changes: 35 additions & 38 deletions packages/tanstackstart-react/src/server/globalMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import {
addNonEnumerableProperty,
captureException,
getActiveSpan,
getClient,
hasSpanStreamingEnabled,
spanToJSON,
updateSpanName,
startSpan,
} from '@sentry/core';
import type { SentryGlobalFunctionMiddleware, SentryGlobalRequestMiddleware } from '../common/types';
import { SENTRY_INTERNAL } from './middleware';
import {
CODE_FUNCTION_NAME,
HTTP_REQUEST_METHOD,
SENTRY_DESCRIPTION,
SENTRY_SEGMENT_NAME_SOURCE,
SENTRY_OP,
SENTRY_ORIGIN,
} from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';

type ServerFnMeta = {
id?: string;
Expand All @@ -37,48 +36,46 @@ function createSentryMiddlewareHandler(mechanismType: string) {
}

function createSentryFunctionMiddlewareHandler(mechanismType: string) {
return async function sentryFunctionMiddlewareHandler({
return function sentryFunctionMiddlewareHandler({
next,
serverFnMeta,
method = 'GET',
}: {
next: () => Promise<unknown>;
serverFnMeta?: ServerFnMeta;
method?: string;
}): Promise<unknown> {
const activeSpan = getActiveSpan();
const spanData = activeSpan ? spanToJSON(activeSpan) : undefined;
if (activeSpan && spanData?.attributes[SENTRY_ORIGIN] === 'auto.function.tanstackstart.server') {
if (serverFnMeta?.name) {
// Read off the attribute rather than the span name, which is low cardinality with span streaming.
const method = (spanData.attributes[HTTP_REQUEST_METHOD] as string | undefined) || 'GET';
const description = `${method} /_serverFn/${serverFnMeta.name}`;
const client = getClient();
const hasSpanStreaming = !!client && hasSpanStreamingEnabled(client);
const functionName = serverFnMeta?.name || 'serverFn';
const description = `${method} /_serverFn/${functionName}`;
const client = getClient();
const hasSpanStreaming = !!client && hasSpanStreamingEnabled(client);

return startSpan(
{
// With span streaming, a `function` span is named after the function it wraps.
updateSpanName(activeSpan, hasSpanStreaming ? serverFnMeta.name : description);
activeSpan.setAttribute(CODE_FUNCTION_NAME, serverFnMeta.name);
if (hasSpanStreaming) {
// Relay infers a `function` span's description from `code.function.name` alone.
activeSpan.setAttribute(SENTRY_DESCRIPTION, description);
name: hasSpanStreaming ? functionName : description,
attributes: {
[SENTRY_ORIGIN]: 'auto.function.tanstackstart.server',
[SENTRY_OP]: FUNCTION,
[CODE_FUNCTION_NAME]: functionName,
[HTTP_REQUEST_METHOD]: method,
// Relay infers a `function` span's description from `code.function.name` alone, which drops the path.
...(hasSpanStreaming && { [SENTRY_DESCRIPTION]: description }),
...(serverFnMeta?.id && { 'tanstackstart.function.id': serverFnMeta.id }),
...(serverFnMeta?.filename && { 'tanstackstart.function.filename': serverFnMeta.filename }),
},
},
async () => {
try {
return await next();
} catch (e) {
captureException(e, {
mechanism: { type: mechanismType, handled: false },
});
throw e;
}
activeSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, 'route');
}
if (serverFnMeta?.id) {
activeSpan.setAttribute('tanstackstart.function.id', serverFnMeta.id);
}
if (serverFnMeta?.filename) {
activeSpan.setAttribute('tanstackstart.function.filename', serverFnMeta.filename);
}
}

try {
return await next();
} catch (e) {
captureException(e, {
mechanism: { type: mechanismType, handled: false },
});
throw e;
}
},
);
};
}

Expand All @@ -98,7 +95,7 @@ export const sentryGlobalRequestMiddleware: SentryGlobalRequestMiddleware = {
};

/**
* Global function middleware that captures errors from server function invocations.
* Global function middleware that creates a span for each server function invocation and captures its errors.
* Should be added as the first entry in the `functionMiddleware` array of `createStart()`.
*/
export const sentryGlobalFunctionMiddleware: SentryGlobalFunctionMiddleware = {
Expand Down
42 changes: 6 additions & 36 deletions packages/tanstackstart-react/src/server/wrapFetchWithSentry.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import { getClient, getTraceMetaTags, hasSpanStreamingEnabled } from '@sentry/core';
import { getTraceMetaTags } from '@sentry/core';
import { flushIfServerless } from '@sentry/core/server';
import { captureException, startSpan } from '@sentry/node';
import {
CODE_FUNCTION_NAME,
HTTP_REQUEST_METHOD,
SENTRY_DESCRIPTION,
SENTRY_OP,
SENTRY_ORIGIN,
} from '@sentry/conventions/attributes';
import { FUNCTION } from '@sentry/conventions/op';
import { captureException } from '@sentry/node';
import { updateSpanWithRouteParametrization } from './routeParametrization';

declare const __SENTRY_ROUTE_PATTERNS__: string[] | undefined;
Expand Down Expand Up @@ -148,32 +140,10 @@ export function wrapFetchWithSentry(serverEntry: ServerEntry): ServerEntry {
const url = new URL(request.url);
const method = request.method || 'GET';

// instrument server functions
if (url.pathname.includes('_serverFn') || url.pathname.includes('createServerFn')) {
const client = getClient();
const hasSpanStreaming = !!client && hasSpanStreamingEnabled(client);
const description = `${method} ${url.pathname}`;

return await startSpan(
{
// With span streaming, a `function` span is named after the function it wraps. The
// request path carries the generated server function id, which is high cardinality.
name: hasSpanStreaming ? 'serverFn' : description,
attributes: {
[SENTRY_ORIGIN]: 'auto.function.tanstackstart.server',
[SENTRY_OP]: FUNCTION,
[CODE_FUNCTION_NAME]: 'serverFn',
// The global function middleware renames this span and needs the method, which it
// can no longer read off a low-cardinality span name.
[HTTP_REQUEST_METHOD]: method,
// Relay infers a `function` span's description from `code.function.name` alone, which drops the path.
...(hasSpanStreaming && { [SENTRY_DESCRIPTION]: description }),
},
},
async () => {
return target.apply(thisArg, args);
},
);
// Server functions are neither routes nor pages: a splat route must not name their request, and their
// response gets no trace meta tags. Their span is created by `sentryGlobalFunctionMiddleware`.
if (url.pathname.includes('_serverFn')) {
return await target.apply(thisArg, args);
}

if (typeof __SENTRY_ROUTE_PATTERNS__ !== 'undefined') {
Expand Down
Loading
Loading