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
Expand Up @@ -4,6 +4,8 @@ import { PAGE_SERVER_RENDERING_TYPE } from '@sentry/conventions/attributes';
import { PAGELOAD } from '@sentry/conventions/op';
import { waitForInitialPageload } from './utils';

const PAGE_SERVER_RENDERING_AGE = 'page.server_rendering.age';

function sentryMetaTagNames(html: string): string[] {
return [...html.matchAll(/<meta name="(sentry-[\w-]+|baggage)"/g)].map(match => match[1] ?? '');
}
Expand All @@ -22,7 +24,7 @@ test.describe('SDK-internal behavior', () => {
});

[
{ path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin'] },
{ path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin', 'sentry-render-start'] },
{ path: '/prerendered-shell', kind: 'a prerendered client-side shell', expected: [] },
{ path: '/', kind: 'a server-rendered page', expected: ['sentry-trace', 'baggage'] },
].forEach(({ path, kind, expected }) => {
Expand All @@ -39,9 +41,14 @@ test.describe('SDK-internal behavior', () => {
});

await page.goto('/prerendered');
const renderStart = Number(await page.locator('meta[name="sentry-render-start"]').getAttribute('content'));
const pageloadTxn = await pageloadTxnPromise;

expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_TYPE]).toBe('static');
// The build rendered the page, so the age is the time since the build.
expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_AGE]).toBe(
Math.max(0, Math.floor(pageloadTxn.start_timestamp! - renderStart)),
);
expect(pageloadTxn.contexts?.trace?.links).toBeUndefined();
expect(pageloadTxn.contexts?.trace?.parent_span_id).toBeUndefined();
});
Expand All @@ -55,6 +62,7 @@ test.describe('SDK-internal behavior', () => {
const pageloadTxn = await pageloadTxnPromise;

expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_TYPE]).toBeUndefined();
expect(pageloadTxn.contexts?.trace?.data?.[PAGE_SERVER_RENDERING_AGE]).toBeUndefined();
expect(pageloadTxn.contexts?.trace?.parent_span_id).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
import { expect, test } from '@playwright/test';
import { expect, test, type Page } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { PAGE_SERVER_RENDERING_TYPE, SENTRY_LINK_TYPE } from '@sentry/conventions/attributes';
import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op';

const PAGE_SERVER_RENDERING_AGE = 'page.server_rendering.age';

function expectedRenderAge(pageloadStart: number, renderStart: number): number {
return Math.max(0, Math.floor(pageloadStart - renderStart));
}

async function getRenderStart(page: Page): Promise<number> {
return Number(await page.locator('meta[name="sentry-render-start"]').getAttribute('content'));
}

function sentryMetaTagNames(html: string): string[] {
return [...html.matchAll(/<meta name="(sentry-[\w-]+|baggage)"/g)].map(match => match[1] ?? '');
}

const VERCEL_ISR_HEADERS = { 'x-vercel-isr': '1' };

[
{ path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin'] },
{ path: '/prerendered', kind: 'a prerendered page', expected: ['sentry-cache-origin', 'sentry-render-start'] },
{ path: '/prerendered-shell', kind: 'a prerendered client-side shell', expected: [] },
{ path: '/', kind: 'a server-rendered page', expected: ['sentry-trace', 'baggage'] },
{ path: '/', headers: VERCEL_ISR_HEADERS, kind: 'a Vercel ISR render', expected: ['sentry-cache-origin'] },
{
path: '/',
headers: VERCEL_ISR_HEADERS,
kind: 'a Vercel ISR render',
expected: ['sentry-cache-origin', 'sentry-render-start'],
},
].forEach(({ path, headers, kind, expected }) => {
test(`writes the expected Sentry meta tags into ${kind} (${path})`, async ({ request }) => {
const html = await (await request.get(path, { headers })).text();
Expand All @@ -28,9 +43,15 @@ test('marks the pageload of a prerendered page as statically rendered, without a
});

await page.goto('/prerendered');
const renderStart = await getRenderStart(page);
const pageloadSpan = await pageloadSpanPromise;

expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' });
// The build rendered the page, so the age is the time since the build.
expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(pageloadSpan.start_timestamp, renderStart),
});
expect(pageloadSpan.links).toBeUndefined();
expect(pageloadSpan.parent_span_id).toBeUndefined();
});
Expand All @@ -44,6 +65,7 @@ test("doesn't mark the pageload of a prerendered client-side shell", async ({ pa
const pageloadSpan = await pageloadSpanPromise;

expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toBeUndefined();
expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_AGE]).toBeUndefined();
expect(pageloadSpan.parent_span_id).toBeUndefined();
});

Expand Down Expand Up @@ -76,6 +98,7 @@ test('marks the pageload of a Vercel ISR page as statically rendered and links t
await page.goto('/');
const cacheOrigin = await page.locator('meta[name="sentry-cache-origin"]').getAttribute('content');
const [originTraceId, originSpanId] = cacheOrigin?.split('-') ?? [];
const renderStart = await getRenderStart(page);
const [originSpan, pageloadSpan] = await Promise.all([
waitForStreamedSpan('sveltekit-3', span => span.span_id === originSpanId, requestStart),
pageloadSpanPromise,
Expand All @@ -85,6 +108,12 @@ test('marks the pageload of a Vercel ISR page as statically rendered and links t
expect(getSpanOp(originSpan)).toBe(HTTP_SERVER);
expect(originSpan.is_segment).toBe(true);
expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' });
// The render started with the request that Vercel marked as an ISR render.
expect(renderStart).toBe(Math.floor(originSpan.start_timestamp));
expect(pageloadSpan.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(pageloadSpan.start_timestamp, renderStart),
});
expect(pageloadSpan.parent_span_id).toBeUndefined();
expect(pageloadSpan.trace_id).not.toBe(originTraceId);
expect(pageloadSpan.links).toEqual([
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-t
export { vercelWaitUntil } from './utils/vercelWaitUntil';
export {
_INTERNAL_getCacheOriginMetaTag,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRenderStart,
_INTERNAL_getRootSpanSentryTrace,
} from './utils/cacheOrigin';
Expand Down
20 changes: 18 additions & 2 deletions packages/core/src/utils/cacheOrigin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,24 @@ export function _INTERNAL_getCacheOriginMetaTag(renderTrace: string | undefined)
return `<meta name="${_INTERNAL_CACHE_ORIGIN_META_TAG_NAME}" content="${renderTrace ?? ''}"/>`;
}

/**
* Returns the `sentry-cache-origin` meta tag and the `sentry-render-start` meta tag for the request that rendered the
* page. Without `renderTrace`, the `sentry-cache-origin` tag is empty. `requestStart` is in seconds.
*/
export function _INTERNAL_getCacheOriginMetaTags(renderTrace: string | undefined, requestStart: number): string {
const renderStart = _INTERNAL_getRenderStart(getActiveRootSpan(), requestStart);
return [
`<meta name="${_INTERNAL_CACHE_ORIGIN_META_TAG_NAME}" content="${renderTrace ?? ''}"/>`,
`<meta name="${_INTERNAL_RENDER_START_META_TAG_NAME}" content="${renderStart}"/>`,
].join('\n');
}

/**
* Returns the `sentry-trace` of the request's root span, which a cached page links as its render. Unlike
* `getTraceData()`, it ignores an active child span, such as SvelteKit's `sveltekit.resolve`.
*/
export function _INTERNAL_getRootSpanSentryTrace(): string | undefined {
const activeSpan = getActiveSpan();
return getTraceData({ span: activeSpan && getRootSpan(activeSpan) })['sentry-trace'];
return getTraceData({ span: getActiveRootSpan() })['sentry-trace'];
}

/**
Expand All @@ -50,6 +61,11 @@ export function _INTERNAL_getRenderStart(span: Span | undefined, startWithoutSpa
return Math.floor(span?.isRecording() ? spanToJSON(span).start_timestamp : startWithoutSpan);
}

function getActiveRootSpan(): Span | undefined {
const activeSpan = getActiveSpan();
return activeSpan && getRootSpan(activeSpan);
}

/**
* Sets `page.server_rendering.type` on a pageload whose document has a `sentry-cache-origin` tag, even an
* empty one. Links the render if the tag holds the `sentry-trace` of a sampled render, and sets
Expand Down
50 changes: 40 additions & 10 deletions packages/core/test/lib/utils/cacheOrigin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { setCurrentClient, startSpan } from '../../../src';
import type { StartSpanOptions } from '../../../src/types/startSpanOptions';
import {
_INTERNAL_getCacheOriginMetaTag,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRenderStart,
_INTERNAL_getRootSpanSentryTrace,
_INTERNAL_withCacheOrigin,
Expand Down Expand Up @@ -62,6 +63,29 @@ describe('_INTERNAL_getCacheOriginMetaTag', () => {
});
});

describe('_INTERNAL_getCacheOriginMetaTags', () => {
beforeEach(() => {
initTestClient(1);
});

it('holds the sentry-trace value and the start of the root span while a child span is active', () => {
startSpan({ name: 'GET /pricing', startTime: RENDER_START + 0.9 }, () =>
startSpan({ name: 'sveltekit.resolve', startTime: RENDER_START + 5 }, () => {
expect(_INTERNAL_getCacheOriginMetaTags(`${TRACE_ID}-${SPAN_ID}-1`, REQUEST_START)).toBe(
`<meta name="sentry-cache-origin" content="${TRACE_ID}-${SPAN_ID}-1"/>\n` +
`<meta name="sentry-render-start" content="${RENDER_START}"/>`,
);
}),
);
});

it('has an empty cache origin tag and the request start without a span (prerendered during the build)', () => {
expect(_INTERNAL_getCacheOriginMetaTags(undefined, REQUEST_START + 0.9)).toBe(
`<meta name="sentry-cache-origin" content=""/>\n<meta name="sentry-render-start" content="${REQUEST_START}"/>`,
);
});
});

describe('_INTERNAL_getRootSpanSentryTrace', () => {
beforeEach(() => {
initTestClient(1);
Expand Down Expand Up @@ -220,28 +244,34 @@ describe('_INTERNAL_withCacheOrigin with a sentry-render-start tag', () => {
});
});

// The server writes the tag and the client reads it, so the HTML format must stay readable by the client.
describe('the tag that _INTERNAL_getCacheOriginMetaTag writes', () => {
// The server writes the tags and the client reads them, so the HTML format must stay readable by the client.
describe('the tags that _INTERNAL_getCacheOriginMetaTags writes', () => {
const pageloadStart = Math.floor(browserPerformanceTimeOrigin()! / 1000);

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

it('makes _INTERNAL_withCacheOrigin link the render', () => {
document.head.innerHTML = _INTERNAL_getCacheOriginMetaTag(`${TRACE_ID}-${SPAN_ID}-1`);
function writeTags(renderTrace: string | undefined): void {
document.head.innerHTML = _INTERNAL_getCacheOriginMetaTags(renderTrace, pageloadStart - 42);
}

it('make _INTERNAL_withCacheOrigin link the render and set its age', () => {
writeTags(`${TRACE_ID}-${SPAN_ID}-1`);

expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toEqual({
name: '/pricing',
attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' },
...spanOptions,
attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static', [PAGE_SERVER_RENDERING_AGE]: 42 },
links: [cacheOriginLink],
});
});

it('makes _INTERNAL_withCacheOrigin set the rendering type without a link when it is empty', () => {
document.head.innerHTML = _INTERNAL_getCacheOriginMetaTag(undefined);
it('make _INTERNAL_withCacheOrigin set the rendering type and age without a link when the cache origin is empty', () => {
writeTags(undefined);

expect(_INTERNAL_withCacheOrigin(spanOptions, 'static')).toEqual({
name: '/pricing',
attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static' },
...spanOptions,
attributes: { [SENTRY_OP]: PAGELOAD, [PAGE_SERVER_RENDERING_TYPE]: 'static', [PAGE_SERVER_RENDERING_AGE]: 42 },
});
});
});
16 changes: 12 additions & 4 deletions packages/sveltekit/src/server-common/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
setHttpStatus,
spanToJSON,
startSpan,
timestampInSeconds,
updateSpanName,
winterCGHeadersToDict,
winterCGRequestToRequestData,
Expand All @@ -21,7 +22,7 @@ import {
} from '@sentry/core';
import {
flushIfServerless,
_INTERNAL_getCacheOriginMetaTag,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRootSpanSentryTrace,
_INTERNAL_handleServedTunnelRequest as handleServedTunnelRequest,
_INTERNAL_setTunnelDefaults as setTunnelDefaults,
Expand Down Expand Up @@ -84,9 +85,11 @@ export const FETCH_PROXY_SCRIPT = `
export function addSentryCodeToPage(options: {
injectFetchProxyScript: boolean;
isVercelIsrRender?: boolean;
/** When the request started, in seconds. Kit calls `transformPageChunk` only after the whole render. */
requestStart: number;
}): NonNullable<ResolveOptions['transformPageChunk']> {
return ({ html }) => {
const metaTags = getPageMetaTags(html, !!options.isVercelIsrRender);
const metaTags = getPageMetaTags(html, !!options.isVercelIsrRender, options.requestStart);
const headWithMetaTags = metaTags ? `<head>\n${metaTags}` : '<head>';

const headWithFetchScript = options.injectFetchProxyScript ? `\n<script>${FETCH_PROXY_SCRIPT}</script>` : '';
Expand All @@ -102,7 +105,7 @@ export function addSentryCodeToPage(options: {
* that many visitors get, such as a prerendered or ISR page, gets `sentry-cache-origin` instead, so each
* pageload starts its own trace.
*/
function getPageMetaTags(html: string, isVercelIsrRender: boolean): string {
function getPageMetaTags(html: string, isVercelIsrRender: boolean, requestStart: number): string {
if (!isVercelIsrRender && !isSvelteKitBuilding()) {
return getTraceMetaTags();
}
Expand All @@ -115,7 +118,10 @@ function getPageMetaTags(html: string, isVercelIsrRender: boolean): string {

// The build does not reliably send spans, so a prerendered page has no trace to link.
// The empty tag still marks the pageload as static.
return _INTERNAL_getCacheOriginMetaTag(isVercelIsrRender ? _INTERNAL_getRootSpanSentryTrace() : undefined);
return _INTERNAL_getCacheOriginMetaTags(
isVercelIsrRender ? _INTERNAL_getRootSpanSentryTrace() : undefined,
requestStart,
);
}

/** Kit writes `node_ids` only if the server rendered content, not for `ssr = false` or the SPA fallback. */
Expand Down Expand Up @@ -174,6 +180,7 @@ async function instrumentHandle(
},
options: SentryHandleOptions,
): Promise<Response> {
const requestStart = timestampInSeconds();
const routeId = event.route?.id;

if (!routeId && !options.handleUnknownRoutes) {
Expand Down Expand Up @@ -258,6 +265,7 @@ async function instrumentHandle(
// Vercel sets this on every ISR invocation, also on revalidation.
// A client that sends it changes only its own response.
isVercelIsrRender: event.request.headers.has('x-vercel-isr'),
requestStart,
}),
});

Expand Down
Loading
Loading