Skip to content

Commit 46be544

Browse files
authored
feat(hono): Instrument main-app inline middleware spans (#20999)
The Hono SDK already instruments `.use` (for middleware) but not yet the HTTP method inline middleware. See more here: https://hono.dev/docs/guides/middleware#definition-of-middleware This PR also adds some additional test cases for existing tests to make the tests more robust. <img width="1192" height="366" alt="image" src="https://github.com/user-attachments/assets/ec3668c6-55bd-474c-8030-58b5e05337cd" />
1 parent 4e0c529 commit 46be544

7 files changed

Lines changed: 458 additions & 11 deletions

File tree

‎dev-packages/e2e-tests/test-applications/hono-4/src/routes.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,39 @@ export function addRoutes(app: HonoType<{ Bindings?: { E2E_TEST_DSN: string } }>
4444
// Inline middleware patterns: direct method, .all(), .on() with inline/separate middleware
4545
app.route('/test-inline-middleware', subAppWithInlineMiddleware);
4646

47+
// Inline middleware on the main app via HTTP method registration (not .use()).
48+
app.get(
49+
'/test-main-inline/get',
50+
async function mainInlineGet(_c, next) {
51+
await next();
52+
},
53+
c => c.text('main inline get'),
54+
);
55+
app.post(
56+
'/test-main-inline/post',
57+
async function mainInlinePost(_c, next) {
58+
await next();
59+
},
60+
c => c.text('main inline post'),
61+
);
62+
app.all(
63+
'/test-main-inline/all',
64+
async function mainInlineAll(_c, next) {
65+
await next();
66+
},
67+
c => c.text('main inline all'),
68+
);
69+
70+
// Combined: .use() middleware + inline middleware via .get() on the same path.
71+
app.use('/test-main-inline/combined/*', middlewareA);
72+
app.get(
73+
'/test-main-inline/combined/resource',
74+
async function combinedInlineMw(_c, next) {
75+
await next();
76+
},
77+
c => c.text('combined response'),
78+
);
79+
4780
// Route patterns: HTTP methods, .all(), .on(), sync/async, errors
4881
app.route('/test-routes', routePatterns);
4982

‎dev-packages/e2e-tests/test-applications/hono-4/tests/errors.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ test.describe('route handler errors', () => {
3232
expect(errorEvent.transaction).toBe('GET /error/:cause');
3333
expect(errorEvent.request?.method).toBe('GET');
3434
expect(errorEvent.request?.url).toContain('/error/test-cause');
35+
expect(errorEvent.request?.headers).toBeDefined();
3536

3637
expect(errorEvent.contexts?.trace?.trace_id).toBe(transactionEvent.contexts?.trace?.trace_id);
3738
});
@@ -217,7 +218,9 @@ test.describe('nested sub-app errors', () => {
217218
handled: false,
218219
type: 'auto.http.hono.context_error',
219220
});
221+
expect(errorEvent.request?.method).toBe('GET');
220222
expect(errorEvent.request?.url).toContain('/test-errors/nested/child/error');
223+
expect(errorEvent.request?.headers).toBeDefined();
221224
});
222225
});
223226

‎dev-packages/e2e-tests/test-applications/hono-4/tests/middleware.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,70 @@ test.describe('inline middleware spans (sub-app)', () => {
248248
}
249249
}
250250
});
251+
252+
const MAIN_INLINE_PREFIX = '/test-main-inline';
253+
254+
const MAIN_INLINE_CASES = [
255+
{ name: '.get()', path: '/get', method: 'GET', expectedMiddlewareName: 'mainInlineGet' },
256+
{ name: '.post()', path: '/post', method: 'POST', expectedMiddlewareName: 'mainInlinePost' },
257+
{ name: '.all()', path: '/all', method: 'GET', expectedMiddlewareName: 'mainInlineAll' },
258+
] as const;
259+
260+
test.describe('inline middleware spans (main app)', () => {
261+
MAIN_INLINE_CASES.forEach(({ name, path, method, expectedMiddlewareName }) => {
262+
test(`creates middleware span for inline middleware via ${name}`, async ({ baseURL }) => {
263+
const fullPath = `${MAIN_INLINE_PREFIX}${path}`;
264+
265+
const transactionPromise = waitForTransaction(APP_NAME, event => {
266+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `${method} ${fullPath}`;
267+
});
268+
269+
const response = await fetch(`${baseURL}${fullPath}`, { method });
270+
expect(response.status).toBe(200);
271+
272+
const transaction = await transactionPromise;
273+
expect(transaction.transaction).toBe(`${method} ${fullPath}`);
274+
275+
const spans = transaction.spans || [];
276+
const inlineSpan = spans.find(s => s.description === expectedMiddlewareName);
277+
278+
expect(inlineSpan).toBeDefined();
279+
expect(inlineSpan?.op).toBe('middleware.hono');
280+
expect(inlineSpan?.origin).toBe('auto.middleware.hono');
281+
expect(inlineSpan?.status).not.toBe('internal_error');
282+
283+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
284+
expect(middlewareSpans).toHaveLength(1);
285+
});
286+
});
287+
288+
test('creates spans for both .use() middleware and inline middleware via .get()', async ({ baseURL }) => {
289+
const fullPath = `${MAIN_INLINE_PREFIX}/combined/resource`;
290+
291+
const transactionPromise = waitForTransaction(APP_NAME, event => {
292+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `GET ${fullPath}`;
293+
});
294+
295+
const response = await fetch(`${baseURL}${fullPath}`);
296+
expect(response.status).toBe(200);
297+
298+
const transaction = await transactionPromise;
299+
expect(transaction.transaction).toBe(`GET ${fullPath}`);
300+
301+
const spans = transaction.spans || [];
302+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
303+
304+
expect(middlewareSpans).toHaveLength(2);
305+
306+
const [spanA, spanB] = middlewareSpans.sort((a, b) => (a.description ?? '').localeCompare(b.description ?? ''));
307+
expect(spanA?.description).toBe('combinedInlineMw');
308+
expect(spanA?.op).toBe('middleware.hono');
309+
expect(spanA?.origin).toBe('auto.middleware.hono');
310+
expect(spanA?.status).not.toBe('internal_error');
311+
312+
expect(spanB?.description).toBe('middlewareA');
313+
expect(spanB?.op).toBe('middleware.hono');
314+
expect(spanB?.origin).toBe('auto.middleware.hono');
315+
expect(spanB?.status).not.toBe('internal_error');
316+
});
317+
});

‎dev-packages/e2e-tests/test-applications/hono-4/tests/route-patterns.test.ts‎

Lines changed: 74 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ const REGISTRATION_STYLES = [
1111
] as const;
1212

1313
test.describe('HTTP methods', () => {
14-
['POST', 'PUT', 'DELETE', 'PATCH'].forEach(method => {
14+
['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].forEach(method => {
1515
test(`sends transaction for ${method}`, async ({ baseURL }) => {
1616
const transactionPromise = waitForTransaction(APP_NAME, event => {
17-
return event.contexts?.trace?.op === 'http.server' && !!event.transaction?.includes(PREFIX);
17+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `${method} ${PREFIX}`;
1818
});
1919

2020
const response = await fetch(`${baseURL}${PREFIX}`, { method });
@@ -23,15 +23,20 @@ test.describe('HTTP methods', () => {
2323
const transaction = await transactionPromise;
2424
expect(transaction.transaction).toBe(`${method} ${PREFIX}`);
2525
expect(transaction.contexts?.trace?.op).toBe('http.server');
26+
expect(transaction.contexts?.trace?.data?.['sentry.source']).toBe('route');
27+
28+
const spans = transaction.spans || [];
29+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
30+
expect(middlewareSpans).toEqual([]);
2631
});
2732
});
2833
});
2934

3035
test.describe('route registration styles', () => {
3136
REGISTRATION_STYLES.forEach(({ name, path }) => {
32-
test(`${name} sends transaction`, async ({ baseURL }) => {
37+
test(`${name} sends transaction with route source`, async ({ baseURL }) => {
3338
const transactionPromise = waitForTransaction(APP_NAME, event => {
34-
return event.contexts?.trace?.op === 'http.server' && !!event.transaction?.includes(`${PREFIX}${path}`);
39+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `GET ${PREFIX}${path}`;
3540
});
3641

3742
const response = await fetch(`${baseURL}${PREFIX}${path}`);
@@ -40,6 +45,11 @@ test.describe('route registration styles', () => {
4045
const transaction = await transactionPromise;
4146
expect(transaction.transaction).toBe(`GET ${PREFIX}${path}`);
4247
expect(transaction.contexts?.trace?.op).toBe('http.server');
48+
expect(transaction.contexts?.trace?.data?.['sentry.source']).toBe('route');
49+
50+
const spans = transaction.spans || [];
51+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
52+
expect(middlewareSpans).toEqual([]);
4353
});
4454
});
4555

@@ -49,21 +59,74 @@ test.describe('route registration styles', () => {
4959
].forEach(({ name, path }) => {
5060
test(`${name} responds to POST`, async ({ baseURL }) => {
5161
const transactionPromise = waitForTransaction(APP_NAME, event => {
52-
return event.contexts?.trace?.op === 'http.server' && !!event.transaction?.includes(`${PREFIX}${path}`);
62+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `POST ${PREFIX}${path}`;
5363
});
5464

5565
const response = await fetch(`${baseURL}${PREFIX}${path}`, { method: 'POST' });
5666
expect(response.status).toBe(200);
5767

5868
const transaction = await transactionPromise;
5969
expect(transaction.transaction).toBe(`POST ${PREFIX}${path}`);
70+
expect(transaction.contexts?.trace?.data?.['sentry.source']).toBe('route');
71+
72+
const spans = transaction.spans || [];
73+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
74+
expect(middlewareSpans).toEqual([]);
75+
});
76+
});
77+
});
78+
79+
test.describe('request data extraction', () => {
80+
test('includes method, url, and headers on transaction', async ({ baseURL }) => {
81+
const transactionPromise = waitForTransaction(APP_NAME, event => {
82+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `GET ${PREFIX}`;
83+
});
84+
85+
const response = await fetch(`${baseURL}${PREFIX}`);
86+
expect(response.status).toBe(200);
87+
88+
const transaction = await transactionPromise;
89+
expect(transaction.request?.method).toBe('GET');
90+
expect(transaction.request?.url).toContain(PREFIX);
91+
expect(transaction.request?.headers).toBeDefined();
92+
});
93+
94+
test('includes query_string when present', async ({ baseURL }) => {
95+
const transactionPromise = waitForTransaction(APP_NAME, event => {
96+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `GET ${PREFIX}`;
6097
});
98+
99+
const response = await fetch(`${baseURL}${PREFIX}?foo=bar&baz=42`);
100+
expect(response.status).toBe(200);
101+
102+
const transaction = await transactionPromise;
103+
104+
expect(transaction.request?.method).toBe('GET');
105+
expect(transaction.request?.url).toContain(PREFIX);
106+
expect(transaction.request?.query_string).toBe('foo=bar&baz=42');
107+
});
108+
109+
test('includes request data for POST with headers', async ({ baseURL }) => {
110+
const transactionPromise = waitForTransaction(APP_NAME, event => {
111+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `POST ${PREFIX}`;
112+
});
113+
114+
const response = await fetch(`${baseURL}${PREFIX}`, {
115+
method: 'POST',
116+
headers: { 'X-Custom-Header': 'test-value' },
117+
});
118+
expect(response.status).toBe(200);
119+
120+
const transaction = await transactionPromise;
121+
expect(transaction.request?.method).toBe('POST');
122+
expect(transaction.request?.url).toContain(PREFIX);
123+
expect(transaction.request?.headers?.['x-custom-header']).toBe('test-value');
61124
});
62125
});
63126

64127
test('async handler sends transaction', async ({ baseURL }) => {
65128
const transactionPromise = waitForTransaction(APP_NAME, event => {
66-
return event.contexts?.trace?.op === 'http.server' && !!event.transaction?.includes(`${PREFIX}/async`);
129+
return event.contexts?.trace?.op === 'http.server' && event.transaction === `GET ${PREFIX}/async`;
67130
});
68131

69132
const response = await fetch(`${baseURL}${PREFIX}/async`);
@@ -72,4 +135,9 @@ test('async handler sends transaction', async ({ baseURL }) => {
72135
const transaction = await transactionPromise;
73136
expect(transaction.transaction).toBe(`GET ${PREFIX}/async`);
74137
expect(transaction.contexts?.trace?.op).toBe('http.server');
138+
expect(transaction.contexts?.trace?.data?.['sentry.source']).toBe('route');
139+
140+
const spans = transaction.spans || [];
141+
const middlewareSpans = spans.filter(s => s.op === 'middleware.hono');
142+
expect(middlewareSpans).toEqual([]);
75143
});

‎packages/hono/src/shared/applyPatches.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { debug } from '@sentry/core';
22
import type { Env, Hono } from 'hono';
33
import { DEBUG_BUILD } from '../debug-build';
44
import { patchAppRequest } from './patchAppRequest';
5-
import { patchAppUse } from './patchAppUse';
5+
import { patchAppUse, patchHttpMethodHandlers } from './patchAppUse';
66
import { type HonoRoute, type RouteHookHandle, installRouteHookOnPrototype, wrapSubAppMiddleware } from './patchRoute';
77

88
// Lazily set by the first call to earlyPatchHono or applyPatches.
@@ -31,6 +31,9 @@ export function applyPatches<E extends Env>(app: Hono<E>): void {
3131
// `app.use` (instance own property) — wraps middleware at registration time on this instance.
3232
patchAppUse(app);
3333

34+
// `app.get`, `app.post`, … (instance own properties) — wraps inline middleware (all-but-last handler).
35+
patchHttpMethodHandlers(app);
36+
3437
patchAppRequest(app);
3538

3639
_routeHook.activate();

‎packages/hono/src/shared/patchAppUse.ts‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import { DEBUG_BUILD } from '../debug-build';
44
import { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';
55

66
// oxlint-disable-next-line typescript/no-explicit-any
7-
const patchedInstances = new WeakSet<Hono<any>>();
7+
const patchedUseInstances = new WeakSet<Hono<any>>();
8+
// oxlint-disable-next-line typescript/no-explicit-any
9+
const patchedMethodInstances = new WeakSet<Hono<any>>();
10+
11+
const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch', 'all'] as const;
812

913
/**
1014
* Patches `app.use` (instance own property) on a Hono instance to instrument middleware at registration time.
@@ -13,12 +17,12 @@ const patchedInstances = new WeakSet<Hono<any>>();
1317
* Idempotent.
1418
*/
1519
export function patchAppUse<E extends Env>(app: Hono<E>): void {
16-
if (patchedInstances.has(app)) {
20+
if (patchedUseInstances.has(app)) {
1721
DEBUG_BUILD && debug.log('[hono] app.use already patched — skipping.');
1822
return;
1923
}
2024

21-
patchedInstances.add(app);
25+
patchedUseInstances.add(app);
2226

2327
app.use = new Proxy(app.use, {
2428
apply(target: typeof app.use, thisArg: typeof app, args: Parameters<typeof app.use>): ReturnType<typeof app.use> {
@@ -34,3 +38,54 @@ export function patchAppUse<E extends Env>(app: Hono<E>): void {
3438
},
3539
});
3640
}
41+
42+
/**
43+
* Patches HTTP method class fields (get, post, put, delete, options, patch, all) to instrument inline middleware at registration time.
44+
*
45+
* For `app.get('/path', mw1, mw2, handler)`, all handlers except the last are middleware and get wrapped with spans.
46+
* The final handler (the route handler) is already covered by the root http.server transaction.
47+
*/
48+
export function patchHttpMethodHandlers<E extends Env>(app: Hono<E>): void {
49+
if (patchedMethodInstances.has(app)) {
50+
DEBUG_BUILD && debug.log('[hono] HTTP method handlers already patched - skipping.');
51+
return;
52+
}
53+
54+
patchedMethodInstances.add(app);
55+
56+
for (const method of HTTP_METHODS) {
57+
app[method] = new Proxy(app[method], {
58+
apply(target, thisArg, args: unknown[]) {
59+
return Reflect.apply(target, thisArg, wrapInlineMiddleware(args));
60+
},
61+
});
62+
}
63+
64+
app.on = new Proxy(app.on, {
65+
apply(target, thisArg, args: unknown[]) {
66+
// .on(method, path, ...handlers) — first two args are method and path
67+
const [method, path, ...handlers] = args;
68+
return Reflect.apply(target, thisArg, [method, path, ...wrapInlineMiddleware(handlers)]);
69+
},
70+
});
71+
}
72+
73+
/**
74+
* Given `[path?, ...handlers]` or `[...handlers]`, wraps all handlers except the last one with spans.
75+
* The last handler is the route handler and is left as-is.
76+
*/
77+
function wrapInlineMiddleware(args: unknown[]): unknown[] {
78+
const hasPathPrefix = typeof args[0] === 'string';
79+
const handlersStart = hasPathPrefix ? 1 : 0;
80+
const handlers = args.slice(handlersStart) as MiddlewareHandler[];
81+
82+
if (handlers.length <= 1) {
83+
return args;
84+
}
85+
86+
const wrapped = [...args];
87+
for (let i = handlersStart; i < wrapped.length - 1; i++) {
88+
wrapped[i] = wrapMiddlewareWithSpan(wrapped[i] as MiddlewareHandler);
89+
}
90+
return wrapped;
91+
}

0 commit comments

Comments
 (0)