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 @@ -54,10 +54,12 @@ test.describe('tracing in static routes with server islands', () => {
expect(clientPageloadSpan.trace_id).toMatch(/[a-f0-9]{32}/);
expect(clientPageloadSpan.parent_span_id).toBeUndefined();

// The islands render in their own requests, so the document itself is static.
expect(clientPageloadSpan.attributes).toMatchObject({
'sentry.op': { value: 'pageload', type: 'string' },
'sentry.origin': { value: 'auto.pageload.astro', type: 'string' },
'sentry.segment.name.source': { value: 'route', type: 'string' },
'page.server_rendering.type': { value: 'static', type: 'string' },
});

// the pageload trace contains a resource link span for the preloaded server island request.
Expand Down Expand Up @@ -131,6 +133,8 @@ test.describe('tracing in SSR routes with server islands', () => {

expect(clientPageloadSpan.trace_id).toBe(pageRenderSegment.trace_id);
expect(clientPageloadSpan.parent_span_id).toBe(pageRenderSegment.span_id);
expect(await page.locator('meta[name="sentry-cache-origin"]').count()).toBe(0);
expect(clientPageloadSpan.attributes['page.server_rendering.type']).toBeUndefined();

// The island script's `fetch()` gets trace headers, but the browser answers it with the preload response, which
// left before the SDK ran. So the island starts its own trace.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,22 @@ test.describe('tracing in static/pre-rendered routes', () => {
expect(clientPageloadSpan.trace_id).toMatch(/[a-f0-9]{32}/);
expect(clientPageloadSpan.parent_span_id).toBeUndefined();

expect(await page.locator('meta[name="sentry-cache-origin"]').getAttribute('content')).toBe('');

expect(clientPageloadSpan.attributes).toMatchObject({
'sentry.op': { value: 'pageload', type: 'string' },
'sentry.origin': { value: 'auto.pageload.astro', type: 'string' },
'sentry.segment.name.source': { value: 'route', type: 'string' },
'page.server_rendering.type': { value: 'static', type: 'string' },
});
// The build rendered the page, so the age is the time since the build.
const renderStart = Number(await page.locator('meta[name="sentry-render-start"]').getAttribute('content'));
expect(clientPageloadSpan.attributes['page.server_rendering.age']).toEqual({
type: 'integer',
value: Math.max(0, Math.floor(clientPageloadSpan.start_timestamp - renderStart)),
});
// The build sends no spans, so there is no render to link.
expect(clientPageloadSpan.links).toBeUndefined();

await page.waitForTimeout(1000); // wait another sec to ensure no server span is sent

Expand Down
23 changes: 15 additions & 8 deletions packages/astro/src/client/browserTracingIntegration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from '@sentry/browser';
import type { Client, Integration, TransactionSource } from '@sentry/core';
import { debug, hasSpanStreamingEnabled, PAGELOAD_SPAN_NAME_FALLBACK } from '@sentry/core';
import { _INTERNAL_withCacheOrigin } from '@sentry/core/browser';
import { DEBUG_BUILD } from '../debug-build';
import { SENTRY_SEGMENT_NAME_SOURCE, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes';

Expand Down Expand Up @@ -35,14 +36,20 @@ export function browserTracingIntegration(
if (options.instrumentPageLoad != false) {
const { name, source } = getPageloadSpanName(client);

startBrowserTracingPageLoadSpan(client, {
name,
attributes: {
[SENTRY_SEGMENT_NAME_SOURCE]: source,
[SENTRY_ORIGIN]: 'auto.pageload.astro',
...(source === 'route' && { [URL_TEMPLATE]: name }),
},
});
startBrowserTracingPageLoadSpan(
client,
_INTERNAL_withCacheOrigin(
{
name,
attributes: {
[SENTRY_SEGMENT_NAME_SOURCE]: source,
[SENTRY_ORIGIN]: 'auto.pageload.astro',
...(source === 'route' && { [URL_TEMPLATE]: name }),
},
},
'static',
),
);
}
}
},
Expand Down
51 changes: 30 additions & 21 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
setHttpStatus,
spanToJSON,
startSpan,
timestampInSeconds,
winterCGHeadersToDict,
winterCGRequestToRequestData,
withIsolationScope,
Expand All @@ -39,6 +40,7 @@ import {
} from '@sentry/core';
import {
flushIfServerless,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
} from '@sentry/core/server';
import { setHttpServerSpanRouteAttribute } from '@sentry/server-utils';
Expand Down Expand Up @@ -93,10 +95,8 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler =
return tunnelResponse;
}

const isDynamicPageRequest = checkIsDynamicPageRequest(ctx);

// For static (prerendered) routes, we only want to inject the parametrized route meta tags
if (!isDynamicPageRequest) {
if (isPrerenderedRequest(ctx)) {
return handleStaticRoute(ctx, next);
}

Expand All @@ -114,12 +114,11 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler =

async function handleStaticRoute(ctx: APIContext, next: MiddlewareNext): Promise<Response> {
const parametrizedRoute = getParametrizedRoute(ctx);
const requestStart = timestampInSeconds();
try {
const originalResponse = await next();

// We never want to continue a trace here, so we do not inject trace data
// But we do want to inject the parametrized route, as this is used for client-side route parametrization
const metaTagsStr = getMetaTagsStr({ injectTraceData: false, parametrizedRoute });
const metaTagsStr = getMetaTagsStr({ prerenderStart: requestStart, parametrizedRoute });
return injectMetaTagsInResponse(originalResponse, metaTagsStr);
} catch (e) {
sendErrorToSentry(e);
Expand Down Expand Up @@ -157,7 +156,7 @@ async function enhanceHttpServerSpan(ctx: APIContext, next: MiddlewareNext, root

try {
const originalResponse = await next();
const metaTagsStr = getMetaTagsStr({ injectTraceData: true, parametrizedRoute });
const metaTagsStr = getMetaTagsStr({ parametrizedRoute });
return injectMetaTagsInResponse(originalResponse, metaTagsStr);
} catch (e) {
sendErrorToSentry(e);
Expand Down Expand Up @@ -207,7 +206,7 @@ async function instrumentRequestStartHttpServerSpan(

// The integration option wins when set; otherwise `dataCollection.userInfo` decides.
if (options.trackClientIp ?? client.getDataCollectionOptions().userInfo) {
isolationScope.setUser({ ip_address: ctx.clientAddress });
isolationScope.setUser({ ip_address: getClientAddress(ctx) });
}

try {
Expand Down Expand Up @@ -259,7 +258,7 @@ async function instrumentRequestStartHttpServerSpan(
setHttpStatus(span, originalResponse.status);
}

const metaTagsStr = getMetaTagsStr({ injectTraceData: true, parametrizedRoute });
const metaTagsStr = getMetaTagsStr({ parametrizedRoute });
return injectMetaTagsInResponse(originalResponse, metaTagsStr);
} catch (e) {
sendErrorToSentry(e);
Expand Down Expand Up @@ -297,17 +296,21 @@ function addMetaTagToHead(htmlChunk: string, metaTagsStr: string): string {
});
}

/**
* `prerenderStart` is set for a prerendered page, in seconds. Every visitor gets the same prerendered HTML, so it
* must not carry the trace of the render. The empty `sentry-cache-origin` tag marks the pageload as static without a
* link, because the build sends no spans.
*/
function getMetaTagsStr({
injectTraceData,
prerenderStart,
parametrizedRoute,
}: {
injectTraceData: boolean;
prerenderStart?: number;
parametrizedRoute: string | undefined;
}): string {
const parts = [];
if (injectTraceData) {
parts.push(getTraceMetaTags());
}
const parts = [
prerenderStart === undefined ? getTraceMetaTags() : _INTERNAL_getCacheOriginMetaTags(undefined, prerenderStart),
];
if (parametrizedRoute) {
parts.push(`<meta name="sentry-route-name" content="${encodeURIComponent(parametrizedRoute)}"/>`);
}
Expand Down Expand Up @@ -398,15 +401,21 @@ function tryDecodeUrl(url: string): string | undefined {
}

/**
* Checks if the incoming request is a request for a dynamic (server-side rendered) page.
* We can check this by looking at the middleware's `clientAddress` context property because accessing
* this prop in a static route will throw an error which we can conveniently catch.
* Astro 5+ sets `isPrerendered`. Older versions only tell a prerendered page by `clientAddress`, which throws
* there. That check also matches on-demand pages on adapters without a client address, so it is the fallback.
*/
function checkIsDynamicPageRequest(context: APIContext): boolean {
function isPrerenderedRequest(context: APIContext & { isPrerendered?: boolean }): boolean {
if (typeof context.isPrerendered === 'boolean') {
return context.isPrerendered;
}
return getClientAddress(context) == null;
}

function getClientAddress(context: APIContext): string | undefined {
try {
return context.clientAddress != null;
return context.clientAddress;
} catch {
return false;
return undefined;
}
}

Expand Down
62 changes: 62 additions & 0 deletions packages/astro/test/client/browserTracingIntegration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* @vitest-environment jsdom
*/

import * as SentryBrowser from '@sentry/browser';
import { PAGE_SERVER_RENDERING_TYPE, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from '@sentry/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { browserTracingIntegration } from '../../src/client/browserTracingIntegration';

const fakeClient = { getOptions: () => ({}), on: () => {}, addEventProcessor: () => {} };

function addCacheOriginMetaTag(content: string): void {
const meta = document.createElement('meta');
meta.name = _INTERNAL_CACHE_ORIGIN_META_TAG_NAME;
meta.content = content;
document.head.appendChild(meta);
}

describe('browserTracingIntegration', () => {
const startBrowserTracingPageLoadSpanSpy = vi
.spyOn(SentryBrowser, 'startBrowserTracingPageLoadSpan')
.mockImplementation(() => ({}) as Span);

beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
document.head.innerHTML = '';
});

it('marks the pageload of a prerendered page as static', () => {
addCacheOriginMetaTag('');

// @ts-expect-error - the fakeClient doesn't satisfy Client but that's fine
browserTracingIntegration().afterAllSetup(fakeClient);

expect(startBrowserTracingPageLoadSpanSpy).toHaveBeenCalledWith(
fakeClient,
expect.objectContaining({
attributes: expect.objectContaining({
[SENTRY_ORIGIN]: 'auto.pageload.astro',
[PAGE_SERVER_RENDERING_TYPE]: 'static',
}),
}),
);
});

it('does not mark the pageload of a page rendered for this request', () => {
// @ts-expect-error - the fakeClient doesn't satisfy Client but that's fine
browserTracingIntegration().afterAllSetup(fakeClient);

expect(startBrowserTracingPageLoadSpanSpy).toHaveBeenCalledWith(
fakeClient,
expect.objectContaining({
attributes: expect.not.objectContaining({ [PAGE_SERVER_RENDERING_TYPE]: expect.anything() }),
}),
);
});
});
33 changes: 31 additions & 2 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ describe('sentryMiddleware', () => {
});
});

it('does not inject tracing <meta> tags if route is static', async () => {
it('injects an empty cache origin <meta> tag instead of tracing <meta> tags if route is static', async () => {
const middleware = handleRequest();

const ctx = STATIC_REQUEST_CONTEXT;
Expand All @@ -463,11 +463,38 @@ describe('sentryMiddleware', () => {
expect(html).toContain('<meta name="something" content=""/></head>');
// parametrized route is injected
expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/>');
// trace data is not injected
expect(html).toContain('<meta name="sentry-cache-origin" content=""/>');
expect(html).toMatch(/<meta name="sentry-render-start" content="\d+"\/>/);
expect(html).not.toContain('<meta name="sentry-trace" content="');
expect(html).not.toContain('<meta name="baggage" content="');
});

it.each([
[
'an on-demand page on an adapter without a client address',
{
...DYNAMIC_REQUEST_CONTEXT,
isPrerendered: false,
get clientAddress(): string {
throw new Error('This adapter has no client address');
},
},
false,
],
['a prerendered page that has a client address', { ...DYNAMIC_REQUEST_CONTEXT, isPrerendered: true }, true],
])('decides by `isPrerendered` for %s', async (_, ctx, isPrerendered) => {
const middleware = handleRequest({ trackClientIp: true });
const next = vi.fn(() =>
Promise.resolve(new Response('<head></head>', { headers: new Headers({ 'content-type': 'text/html' }) })),
);

// @ts-expect-error, a partial ctx object is fine here
const html = await (await middleware(ctx, next))?.text();

expect(html?.includes('<meta name="sentry-cache-origin" content=""/>')).toBe(isPrerendered);
expect(html?.includes('<meta name="sentry-trace" content="')).toBe(!isPrerendered);
});

it('injects routing <meta> tag into the HTML of a pageload response without Sentry being initialized', async () => {
vi.spyOn(SentryCore, 'getClient').mockImplementation(() => undefined);

Expand Down Expand Up @@ -524,6 +551,8 @@ describe('sentryMiddleware', () => {
expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/>');
expect(html).toContain('<meta name="sentry-trace" content="');
expect(html).toContain('<meta name="baggage" content="');
expect(html).not.toContain('sentry-cache-origin');
expect(html).not.toContain('sentry-render-start');
});

it('preserves response status, statusText, and all headers when injecting meta tags', async () => {
Expand Down
Loading