Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions dev-packages/e2e-tests/test-applications/hono-4/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ export function addRoutes(app: HonoType<{ Bindings?: { E2E_TEST_DSN: string } }>

app.basePath('/test-basepath').route('/v1', apiSubApp);

app.use(async function trailingMiddleware(_c, next) {
// Trailing middleware to make sure the route names are resolved correctly (not `/*`).
await new Promise(resolve => setTimeout(resolve, 50));
await next();
});

// .use() on the cloned instance returned by .basePath() — the clone has its own
// .use class field, so this tests whether middleware instrumentation propagates.
app
Expand Down
29 changes: 18 additions & 11 deletions packages/hono/src/shared/middlewareHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,20 @@ import {
winterCGRequestToRequestData,
} from '@sentry/core';
import type { Context } from 'hono';
import { routePath } from 'hono/route';
import { hasFetchEvent } from '../utils/hono-context';
import { defaultShouldHandleError } from './defaultShouldHandleError';
import { resolveRouteName } from './resolveRouteName';
import { type SentryHonoMiddlewareOptions } from '../shared/types';
import { type GetConnInfo } from 'hono/conninfo';

/**
* Request handler for Hono framework
*/
export function requestHandler(context: Context, getConnInfo?: GetConnInfo): void {
const defaultScope = getDefaultIsolationScope();
const currentIsolationScope = getIsolationScope();

const isolationScope = defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;
const isolationScope = getCurrentIsolationScope();

// Set a provisional route name as early as possible so events captured during the request already carry the route.
// It is re-resolved in `responseHandler` once the middleware chain has run.
updateSpanRouteName(isolationScope, context);

isolationScope.setSDKProcessingMetadata({
Expand All @@ -36,6 +35,13 @@ export function requestHandler(context: Context, getConnInfo?: GetConnInfo): voi
}
}

function getCurrentIsolationScope(): Scope {
const defaultScope = getDefaultIsolationScope();
const currentIsolationScope = getIsolationScope();

return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;
}

/**
* Adds HTTP connection info (client IP, port, transport, address type) from Hono's `getConnInfo`
* helper to the root (server) span and the isolation scope.
Expand Down Expand Up @@ -80,6 +86,9 @@ export function responseHandler(
context: Context,
shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],
): void {
// Overwrite the route name now that the middleware chain has run: `routeIndex` is accurate here
updateSpanRouteName(getCurrentIsolationScope(), context);

if (context.error) {
if ((shouldHandleError ?? defaultShouldHandleError)(context.error)) {
getClient()?.captureException(context.error, {
Expand All @@ -90,19 +99,17 @@ export function responseHandler(
}

function updateSpanRouteName(isolationScope: Scope, context: Context): void {
const routeName = `${context.req.method} ${resolveRouteName(context)}`;
const activeSpan = getActiveSpan();

// Final matched route: https://hono.dev/docs/helpers/route#using-with-index-parameter
const lastMatchedRoute = routePath(context, -1);

if (activeSpan) {
activeSpan.updateName(`${context.req.method} ${lastMatchedRoute}`);
activeSpan.updateName(routeName);
activeSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');

const rootSpan = getRootSpan(activeSpan);
updateSpanName(rootSpan, `${context.req.method} ${lastMatchedRoute}`);
updateSpanName(rootSpan, routeName);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
}

isolationScope.setTransactionName(`${context.req.method} ${lastMatchedRoute}`);
isolationScope.setTransactionName(routeName);
}
48 changes: 48 additions & 0 deletions packages/hono/src/shared/resolveRouteName.ts
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)`.

Copy link
Copy Markdown
Member

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

* Heuristics (since Hono has no "isMiddleware" flag):
?

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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);
}
3 changes: 2 additions & 1 deletion packages/hono/test/shared/middlewareHandlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { requestHandler, responseHandler } from '../../src/shared/middlewareHand

vi.mock('hono/route', () => ({
routePath: () => '/test',
matchedRoutes: () => [{ basePath: '/', path: '/test', method: 'GET', handler: (_c: unknown) => undefined }],
}));

vi.mock('../../src/utils/hono-context', () => ({
Expand Down Expand Up @@ -49,7 +50,7 @@ const getActiveSpanMock = SentryCore.getActiveSpan as ReturnType<typeof vi.fn>;

function createMockContext(status: number, error?: Error): unknown {
return {
req: { method: 'GET', raw: new Request('http://localhost/test') },
req: { method: 'GET', routeIndex: 0, raw: new Request('http://localhost/test') },
res: { status },
error,
};
Expand Down
113 changes: 113 additions & 0 deletions packages/hono/test/shared/resolveRouteName.test.ts
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');
});
});
Loading