Skip to content
Merged
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);
}
5 changes: 3 additions & 2 deletions packages/hono/src/shared/patchRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { WrappedFunction } from '@sentry/core';
import type { Hono, MiddlewareHandler } from 'hono';
import { Hono as HonoClass } from 'hono';
import { DEBUG_BUILD } from '../debug-build';
import { isMiddleware } from '../utils/isMiddleware';
import { patchAppRequest } from './patchAppRequest';
import { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';

Expand Down Expand Up @@ -128,8 +129,8 @@ export function wrapSubAppMiddleware(routes: HonoRoute[]): void {

const isLastForGroup = lastIndexByKey.get(`${route.method}\0${route.path}`) === i;

const isMiddleware = !isLastForGroup || (route.method === 'ALL' && route.handler.length >= 2);
if (isMiddleware) {
const isMW = !isLastForGroup || (route.method === 'ALL' && isMiddleware(route.handler));
if (isMW) {
route.handler = wrapMiddlewareWithSpan(route.handler);
}
}
Expand Down
38 changes: 38 additions & 0 deletions packages/hono/src/shared/resolveRouteName.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { Context } from 'hono';
import { matchedRoutes, routePath } from 'hono/route';
import { isMiddleware } from '../utils/isMiddleware';

// Arity alone is enough here (unlike `wrapSubAppMiddleware` in patchRoute.ts, which also needs position)
// We only want the path, and inline middleware shares its handler's path.
function isRouteHandler(handler: unknown): boolean {
return typeof handler === 'function' && !isMiddleware(handler);
}

/**
* 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);
}
26 changes: 26 additions & 0 deletions packages/hono/src/utils/isMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Hono stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers
// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.
// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226
const COMPOSED_HANDLER = '__COMPOSED_HANDLER';

/**
* Infers whether a Hono route entry is a middleware (rather than a route handler).
*
* Hono has no "isMiddleware" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)
* while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped
* first so we check the original handler's arity, not the wrapper's `(c, next)` signature.
* https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8
*
* This is only one signal — callers that must classify inline middleware sharing a method+path with
* their handler (e.g. `wrapSubAppMiddleware`) additionally need positional information.
*/
export function isMiddleware(handler: unknown): boolean {
if (typeof handler !== 'function') {
return false;
}

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;
}
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');
});
});
46 changes: 46 additions & 0 deletions packages/hono/test/utils/isMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { isMiddleware } from '../../src/utils/isMiddleware';

describe('isMiddleware', () => {
it.each([
{ label: 'single-argument route handler (context)', handler: (_c: unknown) => undefined, expected: false },
{
label: 'two-argument middleware (context, next)',
handler: (_c: unknown, _next: unknown) => undefined,
expected: true,
},
])('returns $expected for a $label', ({ handler, expected }) => {
expect(isMiddleware(handler)).toBe(expected);
});

it.each([
{ label: 'undefined', value: undefined },
{ label: 'null', value: null },
{ label: 'plain object with a length property', value: { length: 2 } },
])('returns false for a non-function $label value', ({ value }) => {
expect(isMiddleware(value)).toBe(false);
});

describe('__COMPOSED_HANDLER unwrapping', () => {
it('reports the original arity-1 handler when an arity-2 wrapper composes it', () => {
const wrapped = (_c: unknown, _next: unknown) => undefined;
(wrapped as unknown as Record<string, unknown>).__COMPOSED_HANDLER = (_c: unknown) => undefined;

expect(isMiddleware(wrapped)).toBe(false);
});

it('reports middleware when the unwrapped original is itself arity 2', () => {
const wrapped = (_c: unknown, _next: unknown) => undefined;
(wrapped as unknown as Record<string, unknown>).__COMPOSED_HANDLER = (_c: unknown, _next: unknown) => undefined;

expect(isMiddleware(wrapped)).toBe(true);
});

it('falls back to the wrapper arity when __COMPOSED_HANDLER is not a function', () => {
const handler = (_c: unknown, _next: unknown) => undefined;
(handler as unknown as Record<string, unknown>).__COMPOSED_HANDLER = 'not-a-function';

expect(isMiddleware(handler)).toBe(true);
});
});
});
Loading