Skip to content
Draft
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 @@ -133,6 +133,17 @@ async function getCacheOriginMetaTag(page: Page): Promise<string | null> {
return page.locator('meta[name="sentry-cache-origin"]').getAttribute('content');
}

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

const PAGE_SERVER_RENDERING_AGE = 'page.server_rendering.age';

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

/**
* Tests a page that a route rule caches at runtime. The cached HTML holds the `sentry-trace` value of
* the render in a `sentry-cache-origin` tag. Every pageload starts its own trace, is static, and links
Expand All @@ -154,6 +165,7 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin1 = await getCacheOriginMetaTag(page);
const renderStart1 = await getRenderStart(page);

// === 2. Request (served from the cache) ===
const clientSpanPromise2 = waitForPageloadSegment(routePath);
Expand All @@ -164,6 +176,7 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin2 = await getCacheOriginMetaTag(page);
const renderStart2 = await getRenderStart(page);

const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? [];
const cacheOriginLink = {
Expand Down Expand Up @@ -194,6 +207,19 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(clientSpan1.links).toEqual([cacheOriginLink]);
expect(clientSpan2.links).toEqual([cacheOriginLink]);
});

await test.step('Every pageload has the age of the render, which started with the 1. request', () => {
expect(renderStart1).toBe(Math.floor(serverSpan1.start_timestamp));
expect(renderStart2).toBe(renderStart1);
expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan1.start_timestamp, renderStart1),
});
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan2.start_timestamp, renderStart1),
});
});
}

/**
Expand All @@ -212,6 +238,7 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin1 = await getCacheOriginMetaTag(page);
const renderStart1 = await getRenderStart(page);

const clientSpanPromise2 = waitForPageloadSegment(routePath);
const [_2, clientSpan2] = await Promise.all([
Expand All @@ -220,6 +247,7 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin2 = await getCacheOriginMetaTag(page);
const renderStart2 = await getRenderStart(page);

expect(cacheOrigin1).toBe('');
expect(cacheOrigin2).toBe('');
Expand All @@ -230,4 +258,14 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' });
expect(clientSpan1.links).toBeUndefined();
expect(clientSpan2.links).toBeUndefined();
// The build rendered the page, so the render start is the time of the build.
expect(renderStart2).toBe(renderStart1);
expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan1.start_timestamp, renderStart1),
});
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan2.start_timestamp, renderStart1),
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,17 @@ async function getCacheOriginMetaTag(page: Page): Promise<string | null> {
return page.locator('meta[name="sentry-cache-origin"]').getAttribute('content');
}

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

const PAGE_SERVER_RENDERING_AGE = 'page.server_rendering.age';

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

/**
* Tests a page that a route rule caches at runtime. The cached HTML holds the `sentry-trace` value of
* the render in a `sentry-cache-origin` tag. Every pageload starts its own trace, is static, and links
Expand All @@ -147,6 +158,7 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin1 = await getCacheOriginMetaTag(page);
const renderStart1 = await getRenderStart(page);

// === 2. Request (served from the cache) ===
const clientSpanPromise2 = waitForPageloadSegment(routePath);
Expand All @@ -157,6 +169,7 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin2 = await getCacheOriginMetaTag(page);
const renderStart2 = await getRenderStart(page);

const [originTraceId, originSpanId, originSampled] = cacheOrigin1?.split('-') ?? [];
const cacheOriginLink = {
Expand Down Expand Up @@ -187,6 +200,19 @@ export async function testCacheOriginOnRuntimeCachedPage(
expect(clientSpan1.links).toEqual([cacheOriginLink]);
expect(clientSpan2.links).toEqual([cacheOriginLink]);
});

await test.step('Every pageload has the age of the render, which started with the 1. request', () => {
expect(renderStart1).toBe(Math.floor(serverSpan1.start_timestamp));
expect(renderStart2).toBe(renderStart1);
expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan1.start_timestamp, renderStart1),
});
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan2.start_timestamp, renderStart1),
});
});
}

/**
Expand All @@ -205,6 +231,7 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin1 = await getCacheOriginMetaTag(page);
const renderStart1 = await getRenderStart(page);

const clientSpanPromise2 = waitForPageloadSegment(routePath);
const [_2, clientSpan2] = await Promise.all([
Expand All @@ -213,6 +240,7 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(page.getByText(expectedPageText, { exact: true })).toBeVisible(),
]);
const cacheOrigin2 = await getCacheOriginMetaTag(page);
const renderStart2 = await getRenderStart(page);

expect(cacheOrigin1).toBe('');
expect(cacheOrigin2).toBe('');
Expand All @@ -223,4 +251,14 @@ export async function testEmptyCacheOriginOnPrerenderedPage(
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_TYPE]).toEqual({ type: 'string', value: 'static' });
expect(clientSpan1.links).toBeUndefined();
expect(clientSpan2.links).toBeUndefined();
// The build rendered the page, so the render start is the time of the build.
expect(renderStart2).toBe(renderStart1);
expect(clientSpan1.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan1.start_timestamp, renderStart1),
});
expect(clientSpan2.attributes?.[PAGE_SERVER_RENDERING_AGE]).toEqual({
type: 'integer',
value: expectedRenderAge(clientSpan2.start_timestamp, renderStart1),
});
}
1 change: 0 additions & 1 deletion packages/core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export { isNodeEnv, loadModule } from './utils/node';
export { filenameIsInApp, node, nodeStackLineParser } from './utils/node-stack-trace';
export { vercelWaitUntil } from './utils/vercelWaitUntil';
export {
_INTERNAL_getCacheOriginMetaTag,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRenderStart,
_INTERNAL_getRootSpanSentryTrace,
Expand Down
5 changes: 0 additions & 5 deletions packages/core/src/utils/cacheOrigin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ export const _INTERNAL_RENDER_START_META_TAG_NAME = 'sentry-render-start';
// TODO: Use the constant from `@sentry/conventions` when https://github.com/getsentry/sentry-conventions/pull/799 is released.
const PAGE_SERVER_RENDERING_AGE = 'page.server_rendering.age';

/** Returns the `sentry-cache-origin` meta tag. Without `renderTrace`, the tag is empty. */
export function _INTERNAL_getCacheOriginMetaTag(renderTrace: string | undefined): string {
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.
Expand Down
13 changes: 0 additions & 13 deletions packages/core/test/lib/utils/cacheOrigin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { setCurrentClient, startSpan } from '../../../src';
import type { StartSpanOptions } from '../../../src/types/startSpanOptions';
import {
_INTERNAL_getCacheOriginMetaTag,
_INTERNAL_getCacheOriginMetaTags,
_INTERNAL_getRenderStart,
_INTERNAL_getRootSpanSentryTrace,
Expand Down Expand Up @@ -51,18 +50,6 @@ function initTestClient(tracesSampleRate: number): void {
client.init();
}

describe('_INTERNAL_getCacheOriginMetaTag', () => {
it('holds the sentry-trace value of the render', () => {
expect(_INTERNAL_getCacheOriginMetaTag(`${TRACE_ID}-${SPAN_ID}-1`)).toBe(
`<meta name="sentry-cache-origin" content="${TRACE_ID}-${SPAN_ID}-1"/>`,
);
});

it('is empty without a sentry-trace value', () => {
expect(_INTERNAL_getCacheOriginMetaTag(undefined)).toBe('<meta name="sentry-cache-origin" content=""/>');
});
});

describe('_INTERNAL_getCacheOriginMetaTags', () => {
beforeEach(() => {
initTestClient(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse';
import { getCfProperties, getCloudflareProperties, hasCfProperty, isEventType } from '../utils/event-type-check';
import { addSentryPageMetaTags } from '../utils/pageMetaTags';
import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags';

/**
* Sentry Cloudflare Nitro plugin for when using the "cloudflare-pages" preset in Nuxt.
Expand Down Expand Up @@ -145,6 +145,7 @@ export const sentryCloudflareNitroPlugin =

nitroApp.hooks.hook('beforeResponse', updateRouteBeforeResponse);

nitroApp.hooks.hook('request', recordRequestStart);
nitroApp.hooks.hook('render:html', (html: NuxtRenderHTMLContext, { event }: { event: H3Event }) => {
let storedTraceData: ReturnType<typeof getTraceData> | undefined = undefined;

Expand Down
3 changes: 2 additions & 1 deletion packages/nuxt/src/runtime/plugins/sentry.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import type { H3Event } from 'h3';
import type { NitroAppPlugin } from 'nitropack';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { addSentryPageMetaTags } from '../utils/pageMetaTags';
import { addSentryPageMetaTags, recordRequestStart } from '../utils/pageMetaTags';

export default (nitroApp => {
nitroApp.hooks.hook('error', sentryCaptureErrorHook);

nitroApp.hooks.hook('request', recordRequestStart);
nitroApp.hooks.hook('render:html', (html: NuxtRenderHTMLContext, { event }: { event: H3Event }) => {
addSentryPageMetaTags(html.head, event);
});
Expand Down
21 changes: 18 additions & 3 deletions packages/nuxt/src/runtime/utils/pageMetaTags.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { SerializedTraceData } from '@sentry/core';
import { debug, GLOBAL_OBJ } from '@sentry/core';
import { _INTERNAL_getCacheOriginMetaTag, _INTERNAL_getRootSpanSentryTrace } from '@sentry/core/server';
import { debug, GLOBAL_OBJ, timestampInSeconds } from '@sentry/core';
import { _INTERNAL_getCacheOriginMetaTags, _INTERNAL_getRootSpanSentryTrace } from '@sentry/core/server';
import type { H3Event } from 'h3';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { addSentryTracingMetaTags, getEventRequestInfo } from '../utils';
Expand All @@ -12,6 +12,11 @@ export const NUXT_NITRO_PRESET_FLAG = '__SENTRY_NUXT_NITRO_PRESET__';
// `netlify-edge`), Nitro ignores `isr` and renders the page for each request.
const PLATFORM_ISR_PRESETS = new Set(['vercel', 'netlify', 'netlify-legacy', 'netlify-builder']);

interface RequestStartContext {
// In seconds.
_sentryRequestStart?: number;
}

interface RouteRulesContext {
// Nitro v2: the Nuxt renderer writes the merged rules here before `render:html`.
_nitro?: { routeRules?: RouteRules };
Expand All @@ -24,6 +29,15 @@ interface RouteRules {
isr?: unknown;
}

/**
* Records when a request started. Nitro calls `render:html` only after the whole render, so the render start has to be
* taken earlier. The `request` hook also fires for the requests of the prerenderer, and a background revalidation of a
* cached route sees the context of the request that started it.
*/
export function recordRequestStart(event: H3Event): void {
(event.context as RequestStartContext)._sentryRequestStart = timestampInSeconds();
}

/**
* Adds the Sentry meta tags to a rendered page. A page that other visitors get too has a
* `sentry-cache-origin` tag instead of `sentry-trace` and `baggage`, so that no visitor continues the
Expand All @@ -43,7 +57,8 @@ export function addSentryPageMetaTags(
debug.log(`Adding the Sentry cache origin meta tag to the reused page ${getEventRequestInfo(event).path}.`);
// Sentry skips its server init in the prerender build, so a prerendered page has no trace to link.
const renderTrace = isPrerender ? undefined : (traceData?.['sentry-trace'] ?? _INTERNAL_getRootSpanSentryTrace());
head.push(_INTERNAL_getCacheOriginMetaTag(renderTrace));
const requestStart = (event.context as RequestStartContext | undefined)?._sentryRequestStart ?? timestampInSeconds();
head.push(_INTERNAL_getCacheOriginMetaTags(renderTrace, requestStart));
}

// The Nitro prerenderer sends this header with each route it renders (Nitro v2 and v3). h3 v2 deprecates
Expand Down
Loading
Loading