-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix(hono): Name transactions after the matched route handler #21700
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
s1gr1d
wants to merge
2
commits into
develop
Choose a base branch
from
sig/hono-fix-route-names
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
2 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
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
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,48 @@ | ||
| import type { Context } from 'hono'; | ||
| import { matchedRoutes, routePath } from 'hono/route'; | ||
|
|
||
| // Hono stores the unwrapped handler here when it wraps a sub-app handler for a custom `onError`. | ||
| // See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226 | ||
| const COMPOSED_HANDLER = '__COMPOSED_HANDLER'; | ||
|
|
||
| // Hono doesn't flag middleware, so we infer it from arity (# of params): middleware is `(context, next)`, handlers are `(context)`. | ||
| function isRouteHandler(handler: unknown): boolean { | ||
| if (typeof handler !== 'function') { | ||
| return false; | ||
| } | ||
|
|
||
| // Unwrap onError-wrapped handlers so we check the original handler's arity, not the wrapper's | ||
| const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER]; | ||
| const original = typeof composed === 'function' ? composed : handler; | ||
|
|
||
| return (original as (...args: unknown[]) => unknown).length < 2; | ||
|
Member
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. q: is a handler guaranteed to have only one argument and a middleware to have at least 2? |
||
| } | ||
|
|
||
| /** | ||
| * Resolves the route path of the matched handler for the transaction name. | ||
| * | ||
| * Picking the handler (not just `routePath`) avoids two failure modes: a catch-all middleware | ||
| * registered after the handlers (`routePath(c, -1)` would return just `/*`), and a middleware that | ||
| * short-circuits before the handler runs (`routePath(c)` would return the middleware's path). | ||
| */ | ||
| export function resolveRouteName(context: Context): string { | ||
| const routes = matchedRoutes(context); | ||
|
|
||
| // Trust routeIndex when it lands on a handler - to disambiguate overlapping handlers. | ||
| const current = routes[context.req.routeIndex]; | ||
| if (current && isRouteHandler(current.handler)) { | ||
| return current.path; | ||
| } | ||
|
|
||
| // A middleware short-circuited, so routeIndex is stuck on it: fall back to the last matched handler. | ||
| for (let i = routes.length - 1; i >= 0; i--) { | ||
| const route = routes[i]; | ||
| if (route && isRouteHandler(route.handler)) { | ||
| return route.path; | ||
| } | ||
| } | ||
|
|
||
| // No handler matched (middleware-only path) | ||
| // Final matched route: https://hono.dev/docs/helpers/route#using-with-index-parameter | ||
| return routePath(context, -1); | ||
| } | ||
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,113 @@ | ||
| import type { Context } from 'hono'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| const mockMatchedRoutes = vi.fn(); | ||
| const mockRoutePath = vi.fn(); | ||
|
|
||
| vi.mock('hono/route', () => ({ | ||
| matchedRoutes: (c: unknown) => mockMatchedRoutes(c), | ||
| routePath: (c: unknown, index?: number) => mockRoutePath(c, index), | ||
| })); | ||
|
|
||
| import { resolveRouteName } from '../../src/shared/resolveRouteName'; | ||
|
|
||
| type Route = { | ||
| basePath: string; | ||
| path: string; | ||
| method: string; | ||
| handler: (...args: unknown[]) => unknown; | ||
| }; | ||
|
|
||
| // Middleware has the signature `(context, next)` → arity 2 | ||
| // Route handlers are `(context)` → arity (no. of args) 1 | ||
| // `resolveRouteName` relies on this arity difference to tell them apart. | ||
| function mw(path: string, method = 'ALL'): Route { | ||
| return { basePath: '/', path, method, handler: (_c: unknown, _next: unknown) => undefined }; | ||
| } | ||
|
|
||
| function handler(path: string, method = 'GET'): Route { | ||
| return { basePath: '/', path, method, handler: (_c: unknown) => undefined }; | ||
| } | ||
|
|
||
| function ctx(routeIndex: number): Context { | ||
| return { req: { method: 'GET', routeIndex } } as unknown as Context; | ||
| } | ||
|
|
||
| describe('resolveRouteName', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mockRoutePath.mockReturnValue('/fallback'); | ||
| }); | ||
|
|
||
| it('returns the handler path when routeIndex points at a handler (normal flow)', () => { | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), handler('/users/:id')]); | ||
|
|
||
| expect(resolveRouteName(ctx(1))).toBe('/users/:id'); | ||
| }); | ||
|
|
||
| it('ignores a trailing catch-all middleware and uses the handler path', () => { | ||
| // app.use(fn) registered after the handlers → trailing `/*` is the last matched entry. | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), handler('/test-routes'), mw('/*')]); | ||
|
|
||
| expect(resolveRouteName(ctx(1))).toBe('/test-routes'); | ||
| }); | ||
|
|
||
| it('resolves the handler before dispatch when routeIndex still points at the sentry middleware', () => { | ||
| // Provisional pass: routeIndex is 0 (the sentry middleware) and `matchedRoutes` is already populated. | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), handler('/test-routes'), mw('/*')]); | ||
|
|
||
| expect(resolveRouteName(ctx(0))).toBe('/test-routes'); | ||
| }); | ||
|
|
||
| it('falls back to the matched handler when a middleware short-circuits (routeIndex on middleware)', () => { | ||
| // A scoped middleware throws before reaching the handler, so routeIndex stays on the middleware. | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), mw('/test/middleware/*'), handler('/test/middleware'), mw('/*')]); | ||
|
|
||
| expect(resolveRouteName(ctx(1))).toBe('/test/middleware'); | ||
| }); | ||
|
|
||
| it('prefers the responding handler over other matched handlers (overlap)', () => { | ||
| // Both `/users/:id` and a `/*` catch-all handler match; routeIndex disambiguates. | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), handler('/users/:id'), handler('/*')]); | ||
|
|
||
| expect(resolveRouteName(ctx(1))).toBe('/users/:id'); | ||
| }); | ||
|
|
||
| it('detects a sub-app handler wrapped by a custom onError (COMPOSED_HANDLER)', () => { | ||
| // Hono wraps the handler in an arity-2 closure but exposes the original via `__COMPOSED_HANDLER`. | ||
| const wrapped = ((_c: unknown, _next: unknown) => undefined) as Route['handler']; | ||
| (wrapped as unknown as Record<string, unknown>).__COMPOSED_HANDLER = (_c: unknown) => undefined; | ||
|
|
||
| mockMatchedRoutes.mockReturnValue([ | ||
| mw('/*'), | ||
| { basePath: '/', path: '/test/custom-on-error/fail', method: 'GET', handler: wrapped }, | ||
| mw('/*'), | ||
| ]); | ||
|
|
||
| expect(resolveRouteName(ctx(1))).toBe('/test/custom-on-error/fail'); | ||
| }); | ||
|
|
||
| it('falls back to routePath(c, -1) when only middleware matched', () => { | ||
| const context = ctx(1); | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), mw('/test-basepath/v1/*')]); | ||
| mockRoutePath.mockReturnValue('/test-basepath/v1/*'); | ||
|
|
||
| expect(resolveRouteName(context)).toBe('/test-basepath/v1/*'); | ||
| expect(mockRoutePath).toHaveBeenCalledWith(context, -1); | ||
| }); | ||
|
|
||
| it('falls back to routePath(c, -1) when no routes matched', () => { | ||
| const context = ctx(0); | ||
| mockMatchedRoutes.mockReturnValue([]); | ||
| mockRoutePath.mockReturnValue(''); | ||
|
|
||
| expect(resolveRouteName(context)).toBe(''); | ||
| expect(mockRoutePath).toHaveBeenCalledWith(context, -1); | ||
| }); | ||
|
|
||
| it('walks back to the last handler when routeIndex is out of range', () => { | ||
| mockMatchedRoutes.mockReturnValue([mw('/*'), handler('/test-late-get')]); | ||
|
|
||
| expect(resolveRouteName(ctx(5))).toBe('/test-late-get'); | ||
| }); | ||
| }); |
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.
m: why not use the same heuristic already used in
sentry-javascript/packages/hono/src/shared/patchRoute.ts
Line 110 in b54777a