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
@@ -0,0 +1,11 @@
import { expect, test } from '@playwright/test';

test('injects trace meta tags on pageload', async ({ page }) => {
await page.goto('/');

const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content');
expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/);

const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content');
expect(baggageContent).toContain('sentry-trace_id=');
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
import { Outlet, createRootRoute, HeadContent, Scripts } from '@tanstack/react-router';
import { Outlet, createRootRoute, HeadContent, Scripts, useRouterState } from '@tanstack/react-router';

export const Route = createRootRoute({
head: () => ({
Expand All @@ -19,6 +19,10 @@ export const Route = createRootRoute({
component: RootComponent,
});

// Long enough that the SSR stream flushes a chunk boundary inside this attribute, ahead of
// the head. See https://github.com/getsentry/sentry-javascript/issues/23468.
const LONG_ATTRIBUTE = 'x'.repeat(3000);

function RootComponent() {
return (
<RootDocument>
Expand All @@ -28,8 +32,10 @@ function RootComponent() {
}

function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
const pathname = useRouterState({ select: state => state.location.pathname });

return (
<html>
<html {...(pathname.startsWith('/split-head-chunk') ? { 'data-long': LONG_ATTRIBUTE } : {})}>
<head>
<HeadContent />
</head>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createFileRoute } from '@tanstack/react-router';

export const Route = createFileRoute('/split-head-chunk')({
component: SplitHeadChunk,
});

function SplitHeadChunk() {
return (
<main>
<h1>Split head chunk</h1>
<p>The root document carries a long attribute ahead of the head, so the SSR stream splits inside it.</p>
</main>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ test.describe('Trace propagation', () => {
expect(baggageContent).toContain('sentry-sampled=');
});

test('should inject metatags when the SSR stream splits ahead of the head', async ({ page }) => {
await page.goto('/split-head-chunk');

const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content');
expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/);

const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content');
expect(baggageContent).toContain('sentry-trace_id=');

// The attribute that forces the chunk boundary must survive the rewrite intact.
expect(await page.getAttribute('html', 'data-long')).toHaveLength(3000);
});

test('should have trace connection between server and client', async ({ page }) => {
const serverTxPromise = waitForTransaction('tanstackstart-react-cloudflare', transactionEvent => {
return transactionEvent?.contexts?.trace?.op === 'http.server' && transactionEvent?.transaction === 'GET /';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useEffect, type ReactNode } from 'react';
import { Outlet, createRootRoute, HeadContent, Scripts } from '@tanstack/react-router';
import { Outlet, createRootRoute, HeadContent, Scripts, useRouterState } from '@tanstack/react-router';

// Long enough that the SSR stream flushes a chunk boundary inside this attribute, ahead of
// the head. See https://github.com/getsentry/sentry-javascript/issues/23468.
const LONG_ATTRIBUTE = 'x'.repeat(3000);

export const Route = createRootRoute({
head: () => ({
Expand Down Expand Up @@ -36,8 +40,10 @@ function RootComponent() {
}

function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
const pathname = useRouterState({ select: state => state.location.pathname });

return (
<html>
<html {...(pathname.startsWith('/split-head-chunk') ? { 'data-long': LONG_ATTRIBUTE } : {})}>
<head>
<HeadContent />
</head>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createFileRoute } from '@tanstack/react-router';

export const Route = createFileRoute('/split-head-chunk')({
component: SplitHeadChunk,
});

function SplitHeadChunk() {
return (
<main>
<h1>Split head chunk</h1>
<p>The root document carries a long attribute ahead of the head, so the SSR stream splits inside it.</p>
</main>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ test.describe('Trace propagation', () => {
expect(baggageContent).toContain('sentry-sampled=');
});

// The SSR stream splits inside the long attribute that sits ahead of the head, so the meta
// tags are only injected if the transform carries its state across chunks.
// See https://github.com/getsentry/sentry-javascript/issues/23468.
test('should inject metatags when the SSR stream splits ahead of the head', async ({ page }) => {
await page.goto('/split-head-chunk');

const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content');
expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/);

const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content');
expect(baggageContent).toContain('sentry-trace_id=');

// The attribute that forces the chunk boundary must survive the rewrite.
expect(await page.getAttribute('html', 'data-long')).toHaveLength(3000);
});

test('should have trace connection between server and client', async ({ page }) => {
const serverTxPromise = waitForTransaction('tanstackstart-react', transactionEvent => {
return transactionEvent?.contexts?.trace?.op === 'http.server' && transactionEvent?.transaction === 'GET /';
Expand Down
82 changes: 2 additions & 80 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
winterCGHeadersToDict,
withIsolationScope,
} from '@sentry/node';
import { setHttpServerSpanRouteAttribute } from '@sentry/server-utils';
import { injectHtmlIntoHead, setHttpServerSpanRouteAttribute } from '@sentry/server-utils';
import type { APIContext, MiddlewareHandler, MiddlewareNext, RoutePart } from 'astro';

type MiddlewareOptions = {
Expand Down Expand Up @@ -279,26 +279,6 @@ async function instrumentRequestStartHttpServerSpan(
});
}

/**
* This function optimistically assumes that the HTML coming in chunks will not be split
* within the <head> tag. If this still happens, we simply won't replace anything.
*/
function addMetaTagToHead(htmlChunk: string, metaTagsStr: string): string {
if (typeof htmlChunk !== 'string' || !metaTagsStr) {
return htmlChunk;
}

// Skip quoted attribute values so we don't match <head> inside e.g. data-code="...<head>..."
let replaced = false;
return htmlChunk.replace(/"[^"]*"|'[^']*'|(<head>)/g, (match, headTag) => {
if (headTag && !replaced) {
replaced = true;
return `<head>${metaTagsStr}`;
}
return match;
});
}

function getMetaTagsStr({
injectTraceData,
parametrizedRoute,
Expand Down Expand Up @@ -463,63 +443,5 @@ function getParametrizedRoute(ctx: APIContext & { routePattern?: string }): stri
}

function injectMetaTagsInResponse(originalResponse: Response, metaTagsStr: string): Response {
try {
const contentType = originalResponse.headers.get('content-type');

const isPageloadRequest = contentType?.startsWith('text/html');
if (!isPageloadRequest) {
return originalResponse;
}

// Type case necessary b/c the body's ReadableStream type doesn't include
// the async iterator that is actually available in Node
// We later on use the async iterator to read the body chunks
// see https://github.com/microsoft/TypeScript/issues/39051
const originalBody = originalResponse.body as NodeJS.ReadableStream | null;
if (!originalBody) {
return originalResponse;
}

const decoder = new TextDecoder();

const newResponseStream = new ReadableStream({
start: async controller => {
// Assign to a new variable to avoid TS losing the narrower type checked above.
const body = originalBody;

async function* bodyReporter(): AsyncGenerator<string | Buffer> {
try {
for await (const chunk of body) {
yield chunk;
}
} catch (e) {
// Report stream errors coming from user code or Astro rendering.
sendErrorToSentry(e);
throw e;
}
}

try {
for await (const chunk of bodyReporter()) {
const html = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
const modifiedHtml = addMetaTagToHead(html, metaTagsStr);
controller.enqueue(new TextEncoder().encode(modifiedHtml));
}
} catch (e) {
controller.error(e);
} finally {
controller.close();
}
},
});

return new Response(newResponseStream, {
status: originalResponse.status,
statusText: originalResponse.statusText,
headers: new Headers(originalResponse.headers),
});
} catch (e) {
sendErrorToSentry(e);
throw e;
}
return injectHtmlIntoHead(originalResponse, metaTagsStr, sendErrorToSentry);
}
8 changes: 4 additions & 4 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,9 +389,9 @@ describe('sentryMiddleware', () => {
const html = await resultFromNext?.text();

expect(html).toContain('<head>');
expect(html).toContain('<meta name="something" content=""/></head>');
// parametrized route is injected
expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/>');
expect(html).toContain('<meta name="something" content=""/>');
// parametrized route is injected, directly before the closing head tag
expect(html).toContain('<meta name="sentry-route-name" content="%2Fusers"/></head>');
// trace data is not injected
expect(html).not.toContain('<meta name="sentry-trace" content="');
expect(html).not.toContain('<meta name="baggage" content="');
Expand Down Expand Up @@ -449,7 +449,7 @@ describe('sentryMiddleware', () => {
const html = await resultFromNext?.text();

expect(html).toContain('<head>');
expect(html).toContain('<meta name="something" content=""/></head>');
expect(html).toContain('<meta name="something" content=""/>');
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="');
Expand Down
1 change: 1 addition & 0 deletions packages/server-utils/src/exports.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Shared exports not using diagnostics channels
export { setHttpServerSpanRouteAttribute } from './utils/setHttpServerSpanRouteAttribute';
export { injectHtmlIntoHead, injectHtmlIntoHeadStream } from './utils/htmlInjection';
export { setAsyncLocalStorageAsyncContextStrategy } from './async-context';
export { otlpIntegration, getOtlpTracesEndpoint } from './otlp';
export * from './ai';
Loading
Loading