-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(react-router): Add otel instrumentation for server requests #16147
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
chargome
wants to merge
13
commits into
develop
Choose a base branch
from
cg-rr-server-loaders
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.
+412
−7
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
17c5c6c
add instrumentation
chargome 9262008
some attribute cleanup
chargome 78718c9
Merge branch 'develop' into cg-rr-server-loaders
chargome 01abd59
lint
chargome 7d44413
Merge branch 'develop' into cg-rr-server-loaders
chargome 24a3c3f
unit test for instrumentation
chargome a55f023
update op
chargome 7d367d8
update data request tx
chargome 6576120
Merge branch 'develop' into cg-rr-server-loaders
chargome 09e6888
fix merge
chargome 2abcd92
add attr
chargome f579921
update some tests
chargome 56486f1
Merge branch 'develop' into cg-rr-server-loaders
chargome 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
5 changes: 5 additions & 0 deletions
5
...tests/test-applications/react-router-7-framework/app/routes/performance/dynamic-param.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
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
16 changes: 16 additions & 0 deletions
16
...tests/test-applications/react-router-7-framework/app/routes/performance/server-loader.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,16 @@ | ||
import type { Route } from './+types/server-loader'; | ||
|
||
export async function loader() { | ||
await new Promise(resolve => setTimeout(resolve, 500)); | ||
return { data: 'burritos' }; | ||
} | ||
|
||
export default function ServerLoaderPage({ loaderData }: Route.ComponentProps) { | ||
const { data } = loaderData; | ||
return ( | ||
<div> | ||
<h1>Server Loader Page</h1> | ||
<div>{data}</div> | ||
</div> | ||
); | ||
} |
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
111 changes: 111 additions & 0 deletions
111
packages/react-router/src/server/instrumentation/reactRouter.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,111 @@ | ||
import type { InstrumentationConfig } from '@opentelemetry/instrumentation'; | ||
import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation'; | ||
import { | ||
getActiveSpan, | ||
getRootSpan, | ||
logger, | ||
SDK_VERSION, | ||
SEMANTIC_ATTRIBUTE_SENTRY_OP, | ||
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, | ||
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, | ||
startSpan, | ||
} from '@sentry/core'; | ||
import type * as reactRouter from 'react-router'; | ||
import { DEBUG_BUILD } from '../../common/debug-build'; | ||
import { getOpName, getSpanName, isDataRequest, SEMANTIC_ATTRIBUTE_SENTRY_OVERWRITE } from './util'; | ||
|
||
type ReactRouterModuleExports = typeof reactRouter; | ||
|
||
const supportedVersions = ['>=7.0.0']; | ||
const COMPONENT = 'react-router'; | ||
|
||
/** | ||
* Instrumentation for React Router's server request handler. | ||
* This patches the requestHandler function to add Sentry performance monitoring for data loaders. | ||
*/ | ||
export class ReactRouterInstrumentation extends InstrumentationBase<InstrumentationConfig> { | ||
public constructor(config: InstrumentationConfig = {}) { | ||
super('ReactRouterInstrumentation', SDK_VERSION, config); | ||
} | ||
|
||
/** | ||
* Initializes the instrumentation by defining the React Router server modules to be patched. | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/naming-convention | ||
protected init(): InstrumentationNodeModuleDefinition { | ||
const reactRouterServerModule = new InstrumentationNodeModuleDefinition( | ||
COMPONENT, | ||
supportedVersions, | ||
(moduleExports: ReactRouterModuleExports) => { | ||
return this._createPatchedModuleProxy(moduleExports); | ||
}, | ||
(_moduleExports: unknown) => { | ||
// nothing to unwrap here | ||
return _moduleExports; | ||
}, | ||
); | ||
|
||
return reactRouterServerModule; | ||
} | ||
|
||
/** | ||
* Creates a proxy around the React Router module exports that patches the createRequestHandler function. | ||
* This allows us to wrap the request handler to add performance monitoring for data loaders and actions. | ||
*/ | ||
private _createPatchedModuleProxy(moduleExports: ReactRouterModuleExports): ReactRouterModuleExports { | ||
return new Proxy(moduleExports, { | ||
get(target, prop, receiver) { | ||
if (prop === 'createRequestHandler') { | ||
const original = target[prop]; | ||
return function wrappedCreateRequestHandler(this: unknown, ...args: unknown[]) { | ||
const originalRequestHandler = original.apply(this, args); | ||
|
||
return async function wrappedRequestHandler(request: Request, initialContext?: unknown) { | ||
let url: URL; | ||
try { | ||
url = new URL(request.url); | ||
} catch (error) { | ||
return originalRequestHandler(request, initialContext); | ||
} | ||
|
||
// We currently just want to trace loaders and actions | ||
if (!isDataRequest(url.pathname)) { | ||
return originalRequestHandler(request, initialContext); | ||
} | ||
|
||
const activeSpan = getActiveSpan(); | ||
const rootSpan = activeSpan && getRootSpan(activeSpan); | ||
|
||
if (!rootSpan) { | ||
DEBUG_BUILD && logger.debug('No active root span found, skipping tracing for data request'); | ||
return originalRequestHandler(request, initialContext); | ||
} | ||
|
||
// Set the source and overwrite attributes on the root span to ensure the transaction name | ||
// is derived from the raw URL pathname rather than any parameterized route that may be set later | ||
// TODO: try to set derived parameterized route from build here (args[0]) | ||
rootSpan.setAttributes({ | ||
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url', | ||
[SEMANTIC_ATTRIBUTE_SENTRY_OVERWRITE]: `${request.method} ${url.pathname}`, | ||
}); | ||
|
||
return startSpan( | ||
{ | ||
name: getSpanName(url.pathname, request.method), | ||
attributes: { | ||
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.react-router', | ||
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: getOpName(url.pathname, request.method), | ||
}, | ||
}, | ||
() => { | ||
return originalRequestHandler(request, initialContext); | ||
}, | ||
); | ||
}; | ||
}; | ||
} | ||
return Reflect.get(target, prop, receiver); | ||
}, | ||
}); | ||
} | ||
} |
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,53 @@ | ||
/** | ||
* Gets the op name for a request based on whether it's a loader or action request. | ||
* @param pathName The URL pathname to check | ||
* @param requestMethod The HTTP request method | ||
*/ | ||
export function getOpName(pathName: string, requestMethod: string): string { | ||
return isLoaderRequest(pathName, requestMethod) | ||
? 'function.react-router.loader' | ||
: isActionRequest(pathName, requestMethod) | ||
? 'function.react-router.action' | ||
: 'function.react-router'; | ||
} | ||
|
||
/** | ||
* Gets the span name for a request based on whether it's a loader or action request. | ||
* @param pathName The URL pathname to check | ||
* @param requestMethod The HTTP request method | ||
*/ | ||
export function getSpanName(pathName: string, requestMethod: string): string { | ||
return isLoaderRequest(pathName, requestMethod) | ||
? 'Executing Server Loader' | ||
: isActionRequest(pathName, requestMethod) | ||
? 'Executing Server Action' | ||
: 'Unknown Data Request'; | ||
} | ||
|
||
/** | ||
* Checks if the request is a server loader request | ||
* @param pathname The URL pathname to check | ||
* @param requestMethod The HTTP request method | ||
*/ | ||
export function isLoaderRequest(pathname: string, requestMethod: string): boolean { | ||
return isDataRequest(pathname) && requestMethod === 'GET'; | ||
} | ||
|
||
/** | ||
* Checks if the request is a server action request | ||
* @param pathname The URL pathname to check | ||
* @param requestMethod The HTTP request method | ||
*/ | ||
export function isActionRequest(pathname: string, requestMethod: string): boolean { | ||
return isDataRequest(pathname) && requestMethod === 'POST'; | ||
} | ||
|
||
/** | ||
* Checks if the request is a react-router data request | ||
* @param pathname The URL pathname to check | ||
*/ | ||
export function isDataRequest(pathname: string): boolean { | ||
return pathname.endsWith('.data'); | ||
} | ||
|
||
export const SEMANTIC_ATTRIBUTE_SENTRY_OVERWRITE = 'sentry.overwrite-route'; |
28 changes: 28 additions & 0 deletions
28
packages/react-router/src/server/integration/reactRouterServer.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,28 @@ | ||
import { defineIntegration } from '@sentry/core'; | ||
import { generateInstrumentOnce } from '@sentry/node'; | ||
import { ReactRouterInstrumentation } from '../instrumentation/reactRouter'; | ||
|
||
const INTEGRATION_NAME = 'ReactRouterServer'; | ||
|
||
const instrumentReactRouter = generateInstrumentOnce('React-Router-Server', () => { | ||
return new ReactRouterInstrumentation(); | ||
}); | ||
|
||
export const instrumentReactRouterServer = Object.assign( | ||
(): void => { | ||
instrumentReactRouter(); | ||
}, | ||
{ id: INTEGRATION_NAME }, | ||
); | ||
|
||
/** | ||
* Integration capturing tracing data for React Router server functions. | ||
*/ | ||
export const reactRouterServerIntegration = defineIntegration(() => { | ||
return { | ||
name: INTEGRATION_NAME, | ||
setupOnce() { | ||
instrumentReactRouterServer(); | ||
}, | ||
}; | ||
}); |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
want to ship this in a follow-up