Repository navigation
feat(react-router): Support renderToReadableStream in createSentryHandleRequest #25254
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
Open
lfantone
wants to merge
5
commits into
getsentry:develop
Choose a base branch
from
lfantone:feat/react-router-web-stream-handle-request
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6ed5c25
feat(react-router): Support renderToReadableStream in createSentryHan…
lfantone cacf7ce
fix(react-router): Resolve trace meta tags eagerly and share handler …
lfantone 3b2695e
fix(react-router): Avoid the TransformStream constructor in injectTra…
lfantone f5ea496
fix(react-router): Unref the Web Streams handler's abort timer
lfantone b40312a
fix(react-router): Abort the Web Streams render when the request is a…
lfantone 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
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
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,54 +1,10 @@ | ||
| import { getTraceMetaTags } from '@sentry/core'; | ||
| import { isPrerenderRequest } from '../server/serverBuild'; | ||
|
|
||
| export * from '../client'; | ||
|
|
||
| export { wrapSentryHandleRequest } from '../server/wrapSentryHandleRequest'; | ||
| export { | ||
| createSentryServerInstrumentation, | ||
| type CreateSentryServerInstrumentationOptions, | ||
| } from '../server/createServerInstrumentation'; | ||
|
|
||
| /** | ||
| * Injects Sentry trace meta tags into the HTML response by transforming the ReadableStream. | ||
| * This enables distributed tracing by adding trace context to the HTML document head. | ||
| * @param body - ReadableStream containing the HTML response body to modify | ||
| * @returns A new ReadableStream with Sentry trace meta tags injected into the head section | ||
| */ | ||
| export function injectTraceMetaTags(body: ReadableStream): ReadableStream { | ||
| if (isPrerenderRequest()) { | ||
| return body; | ||
| } | ||
|
|
||
| const headClosingTag = '</head>'; | ||
|
|
||
| const reader = body.getReader(); | ||
| const encoder = new TextEncoder(); | ||
| // A single streaming decoder carries incomplete multi-byte sequences across chunk | ||
| // boundaries. A fresh, non-streaming decoder per chunk would flush a split character | ||
| // as U+FFFD, corrupting the response (see https://github.com/whatwg/encoding/issues/184). | ||
| const decoder = new TextDecoder(); | ||
| const stream = new ReadableStream({ | ||
| async pull(controller) { | ||
| const { done, value } = await reader.read(); | ||
|
|
||
| if (done) { | ||
| controller.close(); | ||
| return; | ||
| } | ||
|
|
||
| const html = value instanceof Uint8Array ? decoder.decode(value, { stream: true }) : String(value); | ||
|
|
||
| if (html.includes(headClosingTag)) { | ||
| const modifiedHtml = html.replace(headClosingTag, `${getTraceMetaTags()}${headClosingTag}`); | ||
|
|
||
| controller.enqueue(encoder.encode(modifiedHtml)); | ||
| return; | ||
| } | ||
|
|
||
| controller.enqueue(encoder.encode(html)); | ||
| }, | ||
| }); | ||
|
|
||
| return stream; | ||
| } | ||
| export { createSentryHandleRequestWebStream as createSentryHandleRequest } from '../server/createSentryHandleRequestWebStream'; | ||
| export type { SentryWebStreamHandleRequestOptions } from '../server/handleRequestTypes'; | ||
| export { injectTraceMetaTags } from '../server/injectTraceMetaTags'; |
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
92 changes: 92 additions & 0 deletions
92
packages/react-router/src/server/createSentryHandleRequestWebStream.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,92 @@ | ||
| import { _INTERNAL_safeUnref } from '@sentry/core/server'; | ||
| import React from 'react'; | ||
| import type { AppLoadContext, EntryContext, RouterContextProvider } from 'react-router'; | ||
| import type { | ||
| HandleRequestWithMiddleware, | ||
| HandleRequestWithoutMiddleware, | ||
| RenderToReadableStreamResult, | ||
| SentryWebStreamHandleRequestOptions, | ||
| } from './handleRequestTypes'; | ||
| import { injectTraceMetaTags } from './injectTraceMetaTags'; | ||
| import { wrapSentryHandleRequest } from './wrapSentryHandleRequest'; | ||
|
|
||
| /** | ||
| * Web Streams variant of `createSentryHandleRequest`, for runtimes without Node streams (e.g. Cloudflare Workers). | ||
| * Must not import any Node.js modules. | ||
| */ | ||
| export function createSentryHandleRequestWebStream( | ||
| options: SentryWebStreamHandleRequestOptions, | ||
| ): HandleRequestWithoutMiddleware & HandleRequestWithMiddleware { | ||
| const { | ||
| streamTimeout = 10000, | ||
| renderToReadableStream, | ||
| ServerRouter, | ||
| botRegex = /bot|crawler|spider|googlebot|chrome-lighthouse|baidu|bing|google|yahoo|lighthouse/i, | ||
| getNonce, | ||
| } = options; | ||
|
|
||
| const handleRequest = async function handleRequest( | ||
| request: Request, | ||
| responseStatusCode: number, | ||
| responseHeaders: Headers, | ||
| routerContext: EntryContext, | ||
| loadContext: AppLoadContext | RouterContextProvider, | ||
| ): Promise<Response> { | ||
| let statusCode = responseStatusCode; | ||
| let shellRendered = false; | ||
| const userAgent = request.headers.get('user-agent'); | ||
| const isBot = typeof userAgent === 'string' && botRegex.test(userAgent); | ||
| const isSpaMode = !!(routerContext as { isSpaMode?: boolean }).isSpaMode; | ||
|
|
||
| const nonce = getNonce?.({ request, loadContext }); | ||
| const app = <ServerRouter context={routerContext} url={request.url} nonce={nonce} />; | ||
|
|
||
| const controller = new AbortController(); | ||
| const abortTimer = _INTERNAL_safeUnref(setTimeout(() => controller.abort(), streamTimeout)); | ||
| const abortRender = (): void => controller.abort(request.signal.reason); | ||
| if (request.signal.aborted) { | ||
| abortRender(); | ||
| } else { | ||
| request.signal.addEventListener('abort', abortRender, { once: true }); | ||
| } | ||
| const stopAbortHandling = (): void => { | ||
| clearTimeout(abortTimer); | ||
| request.signal.removeEventListener('abort', abortRender); | ||
| }; | ||
|
|
||
| let body: RenderToReadableStreamResult; | ||
| try { | ||
| body = await renderToReadableStream(app, { | ||
| nonce, | ||
| signal: controller.signal, | ||
| onError(error: unknown) { | ||
| statusCode = 500; | ||
| // Shell errors reject the render promise and get logged by the caller. | ||
| if (shellRendered) { | ||
| // eslint-disable-next-line no-console | ||
| console.error(error); | ||
| } | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| stopAbortHandling(); | ||
| throw error; | ||
| } | ||
|
|
||
| shellRendered = true; | ||
| body.allReady.then(stopAbortHandling, stopAbortHandling); | ||
|
|
||
| if (isBot || isSpaMode) { | ||
| await body.allReady; | ||
| } | ||
|
|
||
| responseHeaders.set('Content-Type', 'text/html'); | ||
|
|
||
| return new Response(injectTraceMetaTags(body), { | ||
| headers: responseHeaders, | ||
| status: statusCode, | ||
| }); | ||
| }; | ||
|
|
||
| return wrapSentryHandleRequest(handleRequest) as HandleRequestWithoutMiddleware & HandleRequestWithMiddleware; | ||
| } | ||
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
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,62 @@ | ||
| import type { ReactNode } from 'react'; | ||
| import type { AppLoadContext, EntryContext, RouterContextProvider, ServerRouter } from 'react-router'; | ||
|
|
||
| type RenderToReadableStreamOptions = { | ||
| [key: string]: unknown; | ||
| nonce?: string; | ||
| signal?: AbortSignal; | ||
| onError?: (error: unknown) => void; | ||
| }; | ||
|
|
||
| export type RenderToReadableStreamResult = ReadableStream & { allReady: Promise<void> }; | ||
|
|
||
| type RenderToReadableStreamFunction = ( | ||
| node: ReactNode, | ||
| options: RenderToReadableStreamOptions, | ||
| ) => Promise<RenderToReadableStreamResult>; | ||
|
|
||
| export interface SentryWebStreamHandleRequestOptions { | ||
| /** | ||
| * Timeout in milliseconds after which the rendering stream will be aborted | ||
| * @default 10000 | ||
| */ | ||
| streamTimeout?: number; | ||
|
|
||
| /** | ||
| * React's renderToReadableStream function from 'react-dom/server' | ||
| */ | ||
| renderToReadableStream: RenderToReadableStreamFunction; | ||
|
|
||
| /** | ||
| * The <ServerRouter /> component from '@react-router/server' | ||
| */ | ||
| ServerRouter: typeof ServerRouter; | ||
|
|
||
| /** | ||
| * Regular expression to identify bot user agents | ||
| * @default /bot|crawler|spider|googlebot|chrome-lighthouse|baidu|bing|google|yahoo|lighthouse/i | ||
| */ | ||
| botRegex?: RegExp; | ||
|
|
||
| /** | ||
| * Returns a Content Security Policy nonce for the current request. | ||
| * The nonce is passed to both `<ServerRouter />` and `renderToReadableStream`. | ||
| */ | ||
| getNonce?: (args: { request: Request; loadContext: AppLoadContext | RouterContextProvider }) => string | undefined; | ||
| } | ||
|
|
||
| export type HandleRequestWithoutMiddleware = ( | ||
| request: Request, | ||
| responseStatusCode: number, | ||
| responseHeaders: Headers, | ||
| routerContext: EntryContext, | ||
| loadContext: AppLoadContext, | ||
| ) => Promise<unknown>; | ||
|
|
||
| export type HandleRequestWithMiddleware = ( | ||
| request: Request, | ||
| responseStatusCode: number, | ||
| responseHeaders: Headers, | ||
| routerContext: EntryContext, | ||
| loadContext: RouterContextProvider, | ||
| ) => Promise<unknown>; |
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.