-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(react-router): Trace propagation #16070
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
67 changes: 9 additions & 58 deletions
67
dev-packages/e2e-tests/test-applications/react-router-7-framework/app/entry.server.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
...ts/test-applications/react-router-7-framework/tests/performance/trace-propagation.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { expect, test } from '@playwright/test'; | ||
import { waitForTransaction } from '@sentry-internal/test-utils'; | ||
import { APP_NAME } from '../constants'; | ||
|
||
test.describe('Trace propagation', () => { | ||
test('should inject metatags in ssr pageload', async ({ page }) => { | ||
await page.goto(`/`); | ||
const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content'); | ||
expect(sentryTraceContent).toBeDefined(); | ||
expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/); | ||
const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content'); | ||
expect(baggageContent).toBeDefined(); | ||
expect(baggageContent).toContain('sentry-environment=qa'); | ||
expect(baggageContent).toContain('sentry-public_key='); | ||
expect(baggageContent).toContain('sentry-trace_id='); | ||
expect(baggageContent).toContain('sentry-transaction='); | ||
expect(baggageContent).toContain('sentry-sampled='); | ||
}); | ||
|
||
test('should have trace connection', async ({ page }) => { | ||
const serverTxPromise = waitForTransaction(APP_NAME, async transactionEvent => { | ||
return transactionEvent.transaction === 'GET *'; | ||
}); | ||
|
||
const clientTxPromise = waitForTransaction(APP_NAME, async transactionEvent => { | ||
return transactionEvent.transaction === '/'; | ||
}); | ||
|
||
await page.goto(`/`); | ||
const serverTx = await serverTxPromise; | ||
const clientTx = await clientTxPromise; | ||
|
||
expect(clientTx.contexts?.trace?.trace_id).toEqual(serverTx.contexts?.trace?.trace_id); | ||
expect(clientTx.contexts?.trace?.parent_span_id).toBe(serverTx.contexts?.trace?.span_id); | ||
}); | ||
}); |
138 changes: 138 additions & 0 deletions
138
packages/react-router/src/server/createSentryHandleRequest.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
import React from 'react'; | ||
import type { AppLoadContext, EntryContext, ServerRouter } from 'react-router'; | ||
import type { ReactNode } from 'react'; | ||
import { getMetaTagTransformer, wrapSentryHandleRequest } from './wrapSentryHandleRequest'; | ||
import type { createReadableStreamFromReadable } from '@react-router/node'; | ||
import { PassThrough } from 'stream'; | ||
|
||
type RenderToPipeableStreamOptions = { | ||
[key: string]: unknown; | ||
onShellReady?: () => void; | ||
onAllReady?: () => void; | ||
onShellError?: (error: unknown) => void; | ||
onError?: (error: unknown) => void; | ||
}; | ||
|
||
type RenderToPipeableStreamResult = { | ||
pipe: (destination: NodeJS.WritableStream) => void; | ||
abort: () => void; | ||
}; | ||
|
||
type RenderToPipeableStreamFunction = ( | ||
node: ReactNode, | ||
options: RenderToPipeableStreamOptions, | ||
) => RenderToPipeableStreamResult; | ||
|
||
export interface SentryHandleRequestOptions { | ||
/** | ||
* Timeout in milliseconds after which the rendering stream will be aborted | ||
* @default 10000 | ||
*/ | ||
streamTimeout?: number; | ||
|
||
/** | ||
* React's renderToPipeableStream function from 'react-dom/server' | ||
*/ | ||
renderToPipeableStream: RenderToPipeableStreamFunction; | ||
|
||
/** | ||
* The <ServerRouter /> component from '@react-router/server' | ||
*/ | ||
ServerRouter: typeof ServerRouter; | ||
|
||
/** | ||
* createReadableStreamFromReadable from '@react-router/node' | ||
*/ | ||
createReadableStreamFromReadable: typeof createReadableStreamFromReadable; | ||
|
||
/** | ||
* Regular expression to identify bot user agents | ||
* @default /bot|crawler|spider|googlebot|chrome-lighthouse|baidu|bing|google|yahoo|lighthouse/i | ||
*/ | ||
botRegex?: RegExp; | ||
} | ||
|
||
/** | ||
* A complete Sentry-instrumented handleRequest implementation that handles both | ||
* route parametrization and trace meta tag injection. | ||
* | ||
* @param options Configuration options | ||
* @returns A Sentry-instrumented handleRequest function | ||
*/ | ||
export function createSentryHandleRequest( | ||
options: SentryHandleRequestOptions, | ||
): ( | ||
request: Request, | ||
responseStatusCode: number, | ||
responseHeaders: Headers, | ||
routerContext: EntryContext, | ||
loadContext: AppLoadContext, | ||
) => Promise<unknown> { | ||
const { | ||
streamTimeout = 10000, | ||
renderToPipeableStream, | ||
ServerRouter, | ||
createReadableStreamFromReadable, | ||
botRegex = /bot|crawler|spider|googlebot|chrome-lighthouse|baidu|bing|google|yahoo|lighthouse/i, | ||
} = options; | ||
|
||
const handleRequest = function handleRequest( | ||
request: Request, | ||
responseStatusCode: number, | ||
responseHeaders: Headers, | ||
routerContext: EntryContext, | ||
_loadContext: AppLoadContext, | ||
): Promise<Response> { | ||
return new Promise((resolve, reject) => { | ||
let shellRendered = false; | ||
const userAgent = request.headers.get('user-agent'); | ||
|
||
// Determine if we should use onAllReady or onShellReady | ||
const isBot = typeof userAgent === 'string' && botRegex.test(userAgent); | ||
const isSpaMode = !!(routerContext as { isSpaMode?: boolean }).isSpaMode; | ||
|
||
const readyOption = isBot || isSpaMode ? 'onAllReady' : 'onShellReady'; | ||
|
||
const { pipe, abort } = renderToPipeableStream(<ServerRouter context={routerContext} url={request.url} />, { | ||
[readyOption]() { | ||
shellRendered = true; | ||
const body = new PassThrough(); | ||
|
||
const stream = createReadableStreamFromReadable(body); | ||
|
||
responseHeaders.set('Content-Type', 'text/html'); | ||
|
||
resolve( | ||
new Response(stream, { | ||
headers: responseHeaders, | ||
status: responseStatusCode, | ||
}), | ||
); | ||
|
||
// this injects trace data to the HTML head | ||
pipe(getMetaTagTransformer(body)); | ||
}, | ||
onShellError(error: unknown) { | ||
reject(error); | ||
}, | ||
onError(error: unknown) { | ||
// eslint-disable-next-line no-param-reassign | ||
responseStatusCode = 500; | ||
// Log streaming rendering errors from inside the shell. Don't log | ||
// errors encountered during initial shell rendering since they'll | ||
// reject and get logged in handleDocumentRequest. | ||
if (shellRendered) { | ||
// eslint-disable-next-line no-console | ||
console.error(error); | ||
} | ||
}, | ||
}); | ||
|
||
// Abort the rendering stream after the `streamTimeout` | ||
setTimeout(abort, streamTimeout); | ||
}); | ||
}; | ||
|
||
// Wrap the handle request function for request parametrization | ||
return wrapSentryHandleRequest(handleRequest); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
export * from '@sentry/node'; | ||
|
||
export { init } from './sdk'; | ||
export { sentryHandleRequest } from './sentryHandleRequest'; | ||
// eslint-disable-next-line deprecation/deprecation | ||
export { wrapSentryHandleRequest, sentryHandleRequest, getMetaTagTransformer } from './wrapSentryHandleRequest'; | ||
export { createSentryHandleRequest, type SentryHandleRequestOptions } from './createSentryHandleRequest'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.