-
Notifications
You must be signed in to change notification settings - Fork 585
fix(express): Ensure 404 routes don't attach route attribute #2843
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
pichlermarc
merged 6 commits into
open-telemetry:main
from
s1gr1d:sigrid/handle-express-404
Jun 13, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
214b126
fix(express): Ensure 404 routes don't attach route attribute
s1gr1d 726cdcf
handle route naming
s1gr1d 1df9019
improve comments
s1gr1d 006539c
consider regex route paths
s1gr1d 2cb552a
run lint
s1gr1d 2b9dd88
Merge branch 'main' into sigrid/handle-express-404
pichlermarc 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 |
---|---|---|
|
@@ -213,3 +213,93 @@ const extractLayerPathSegment = (arg: LayerPathSegment) => { | |
|
||
return; | ||
}; | ||
|
||
export function getConstructedRoute(req: { | ||
originalUrl: PatchedRequest['originalUrl']; | ||
[_LAYERS_STORE_PROPERTY]?: string[]; | ||
}) { | ||
const layersStore: string[] = Array.isArray(req[_LAYERS_STORE_PROPERTY]) | ||
? (req[_LAYERS_STORE_PROPERTY] as string[]) | ||
: []; | ||
|
||
const meaningfulPaths = layersStore.filter( | ||
path => path !== '/' && path !== '/*' | ||
); | ||
|
||
if (meaningfulPaths.length === 1 && meaningfulPaths[0] === '*') { | ||
return '*'; | ||
} | ||
|
||
// Join parts and remove duplicate slashes | ||
return meaningfulPaths.join('').replace(/\/{2,}/g, '/'); | ||
} | ||
|
||
/** | ||
* Extracts the actual matched route from Express request for OpenTelemetry instrumentation. | ||
* Returns the route that should be used as the http.route attribute. | ||
* | ||
* @param req - The Express request object with layers store | ||
* @param layersStoreProperty - The property name where layer paths are stored | ||
* @returns The matched route string or undefined if no valid route is found | ||
*/ | ||
export function getActualMatchedRoute(req: { | ||
originalUrl: PatchedRequest['originalUrl']; | ||
[_LAYERS_STORE_PROPERTY]?: string[]; | ||
}): string | undefined { | ||
const layersStore: string[] = Array.isArray(req[_LAYERS_STORE_PROPERTY]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: same here |
||
? (req[_LAYERS_STORE_PROPERTY] as string[]) | ||
: []; | ||
|
||
// If no layers are stored, no route can be determined | ||
if (layersStore.length === 0) { | ||
return undefined; | ||
} | ||
|
||
// Handle root path case - if all paths are root, only return root if originalUrl is also root | ||
// The layer store also includes root paths in case a non-existing url was requested | ||
if (layersStore.every(path => path === '/')) { | ||
return req.originalUrl === '/' ? '/' : undefined; | ||
} | ||
|
||
const constructedRoute = getConstructedRoute(req); | ||
if (constructedRoute === '*') { | ||
return constructedRoute; | ||
} | ||
|
||
// For RegExp routes or route arrays, return the constructed route | ||
// This handles the case where the route is defined using RegExp or an array | ||
if ( | ||
constructedRoute.includes('/') && | ||
(constructedRoute.includes(',') || | ||
constructedRoute.includes('\\') || | ||
constructedRoute.includes('*') || | ||
constructedRoute.includes('[')) | ||
) { | ||
return constructedRoute; | ||
} | ||
|
||
// Ensure route starts with '/' if it doesn't already | ||
const normalizedRoute = constructedRoute.startsWith('/') | ||
? constructedRoute | ||
: `/${constructedRoute}`; | ||
|
||
// Validate that this appears to be a matched route | ||
// A route is considered matched if: | ||
// 1. We have a constructed route | ||
// 2. The original URL matches or starts with our route pattern | ||
const isValidRoute = | ||
normalizedRoute.length > 0 && | ||
(req.originalUrl === normalizedRoute || | ||
req.originalUrl.startsWith(normalizedRoute) || | ||
isRoutePattern(normalizedRoute)); | ||
|
||
return isValidRoute ? normalizedRoute : undefined; | ||
} | ||
|
||
/** | ||
* Checks if a route contains parameter patterns (e.g., :id, :userId) | ||
* which are valid even if they don't exactly match the original URL | ||
*/ | ||
function isRoutePattern(route: string): boolean { | ||
return route.includes(':') || route.includes('*'); | ||
} |
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.
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.
nit:
_LAYERS_STORE_PROPERTY
is set only instoreLayerPath
function. Meaning that if defined it must be an array. So this const assignment could be simplified to.I see you added a test specifically for a scenario where that property is defined with a non-array value. Probably to avoid a case where another piece of code outside the instrumentation modifies the property. If you want the extra safety of
Array.isArray
it's okay but there is no need to cast types. TS resolves the type properly from the function signature.NOTE: maybe if the instrumentation uses a
Symbol
instead of a string it will ensure no other code could change the layer store