diff --git a/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.serverIslands.test.ts b/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.serverIslands.test.ts index b7274ac72bef..1edcb0cfc338 100644 --- a/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.serverIslands.test.ts +++ b/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.serverIslands.test.ts @@ -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. @@ -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. diff --git a/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.static.test.ts b/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.static.test.ts index 2c28eadd55ad..1de75279fa7b 100644 --- a/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.static.test.ts +++ b/dev-packages/e2e-tests/test-applications/astro-7/tests/tracing.static.test.ts @@ -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 diff --git a/packages/astro/src/client/browserTracingIntegration.ts b/packages/astro/src/client/browserTracingIntegration.ts index 80545c379b2e..10383f9ec274 100644 --- a/packages/astro/src/client/browserTracingIntegration.ts +++ b/packages/astro/src/client/browserTracingIntegration.ts @@ -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'; @@ -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', + ), + ); } } }, diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index c50f53bdc4ac..d6b9dfc2d4d1 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -31,6 +31,7 @@ import { setHttpStatus, spanToJSON, startSpan, + timestampInSeconds, winterCGHeadersToDict, winterCGRequestToRequestData, withIsolationScope, @@ -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'; @@ -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); } @@ -114,12 +114,11 @@ export const handleRequest: (options?: MiddlewareOptions) => MiddlewareHandler = async function handleStaticRoute(ctx: APIContext, next: MiddlewareNext): Promise { 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); @@ -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); @@ -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 { @@ -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); @@ -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(``); } @@ -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; } } diff --git a/packages/astro/test/client/browserTracingIntegration.test.ts b/packages/astro/test/client/browserTracingIntegration.test.ts new file mode 100644 index 000000000000..353875ef2199 --- /dev/null +++ b/packages/astro/test/client/browserTracingIntegration.test.ts @@ -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() }), + }), + ); + }); +}); diff --git a/packages/astro/test/server/middleware.test.ts b/packages/astro/test/server/middleware.test.ts index 2c4b625b86e9..082c9af75ef7 100644 --- a/packages/astro/test/server/middleware.test.ts +++ b/packages/astro/test/server/middleware.test.ts @@ -440,7 +440,7 @@ describe('sentryMiddleware', () => { }); }); - it('does not inject tracing tags if route is static', async () => { + it('injects an empty cache origin tag instead of tracing tags if route is static', async () => { const middleware = handleRequest(); const ctx = STATIC_REQUEST_CONTEXT; @@ -463,11 +463,38 @@ describe('sentryMiddleware', () => { expect(html).toContain(''); // parametrized route is injected expect(html).toContain(''); - // trace data is not injected + expect(html).toContain(''); + expect(html).toMatch(//); expect(html).not.toContain('')).toBe(isPrerendered); + expect(html?.includes(''); expect(html).toContain('