Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
28 changes: 28 additions & 0 deletions src/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,34 @@ export function tracingPlugin(traceOpts?: TracingPluginOptions): H3Plugin {
} satisfies H3Route;
});

// Wrap route handlers returned by ~findRoute so frameworks that resolve
// routes at request time (e.g. nitro file-based routes) without pushing
// into ~routes still emit route traces. A fresh wrapper is rebuilt on
// every assignment so previously-captured references stay stable — a
// framework pattern like `const prev = app["~findRoute"]; app["~findRoute"]
// = (e) => prev(e)` must not recurse into itself.
const wrapFindRoute = (fn: H3Core["~findRoute"]): H3Core["~findRoute"] => {
return (event: H3Event) => {
const route = fn.call(h3, event);
if (route?.data.handler) {
route.data.handler = wrapEventHandler(route.data.handler);
}
if (route?.data.middleware) {
route.data.middleware = route.data.middleware.map((m) => wrapMiddleware(m));
}
return route;
};
};
let wrappedFindRoute = wrapFindRoute(h3["~findRoute"]);
Object.defineProperty(h3, "~findRoute", {
configurable: true,
enumerable: false,
get: () => wrappedFindRoute,
set: (fn: H3Core["~findRoute"]) => {
wrappedFindRoute = wrapFindRoute(fn);
},
});

if ("on" in h3 && typeof h3.on === "function") {
const originalOn = h3.on;

Expand Down
187 changes: 187 additions & 0 deletions test/tracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1156,4 +1156,191 @@ describe("tracing channels for H3Core instances", () => {
listener.cleanup();
}
});

it("traces handlers returned from a custom ~findRoute (nitro-style file routes)", async () => {
const listener = createTracingListener();
const { H3Core } = await import("../src/h3.ts");
const { tracingPlugin } = await import("../src/tracing.ts");
const { H3Event } = await import("../src/event.ts");

try {
const app = new H3Core();
const routeHandler = () => "file-based response";

// Simulate a framework that resolves routes at request time and never
// pushes them into app["~routes"]. The handler only exists inside the
// custom ~findRoute implementation.
app["~findRoute"] = (event: any) => {
if (event.url.pathname === "/file-route" && event.req.method === "GET") {
return {
data: {
method: "GET",
route: "/file-route",
handler: routeHandler,
},
params: {},
};
}
return undefined;
};

// Apply tracing plugin after ~findRoute is set (mirrors the order
// documented in the suggested fix).
tracingPlugin()(app as any);

const request = new Request("http://localhost/file-route", { method: "GET" });
const event = new H3Event(request, undefined, app as any);

await app.handler(event);

await new Promise((resolve) => setTimeout(resolve, 10));

const routeEvents = listener.events.filter((e) => e.asyncStart?.data.type === "route");

expect(routeEvents.some((e) => e.asyncStart?.data.event.url.pathname === "/file-route")).toBe(
true,
);
} finally {
listener.cleanup();
}
});

it("traces handlers when ~findRoute is reassigned after tracingPlugin is applied", async () => {
const listener = createTracingListener();
const { H3Core } = await import("../src/h3.ts");
const { tracingPlugin } = await import("../src/tracing.ts");
const { H3Event } = await import("../src/event.ts");

try {
const app = new H3Core();
const routeHandler = () => "late-bound response";

// Apply plugin BEFORE the framework wires up routing (typical nitro
// order: plugins register, then file-based routing installs ~findRoute).
tracingPlugin()(app as any);

app["~findRoute"] = (event: any) => {
if (event.url.pathname === "/late-route" && event.req.method === "GET") {
return {
data: {
method: "GET",
route: "/late-route",
handler: routeHandler,
},
params: {},
};
}
return undefined;
};

const request = new Request("http://localhost/late-route", { method: "GET" });
const event = new H3Event(request, undefined, app as any);

await app.handler(event);
await new Promise((resolve) => setTimeout(resolve, 10));

const routeEvents = listener.events.filter((e) => e.asyncStart?.data.type === "route");
expect(routeEvents.some((e) => e.asyncStart?.data.event.url.pathname === "/late-route")).toBe(
true,
);
} finally {
listener.cleanup();
}
});

it("keeps ~findRoute non-enumerable after tracingPlugin is applied", async () => {
const { H3Core } = await import("../src/h3.ts");
const { tracingPlugin } = await import("../src/tracing.ts");

const app = new H3Core();
tracingPlugin()(app as any);

expect(Object.keys(app)).not.toContain("~findRoute");
const descriptor = Object.getOwnPropertyDescriptor(app, "~findRoute");
expect(descriptor?.enumerable).toBe(false);
});

it("does not recurse when a framework wraps ~findRoute via captured reference", async () => {
const listener = createTracingListener();
const { H3Core } = await import("../src/h3.ts");
const { tracingPlugin } = await import("../src/tracing.ts");
const { H3Event } = await import("../src/event.ts");

try {
const app = new H3Core();
const routeHandler = () => "ok";

tracingPlugin()(app as any);

// Common framework pattern: capture current ~findRoute then replace with
// a wrapper that delegates to the captured reference. Must not recurse.
const prev = app["~findRoute"];
app["~findRoute"] = (event: any) => {
const matched = prev.call(app, event);
if (matched) return matched;
if (event.url.pathname === "/wrapped" && event.req.method === "GET") {
return {
data: { method: "GET", route: "/wrapped", handler: routeHandler },
params: {},
};
}
return undefined;
};

const request = new Request("http://localhost/wrapped", { method: "GET" });
const event = new H3Event(request, undefined, app as any);

await app.handler(event);
await new Promise((resolve) => setTimeout(resolve, 10));

const routeEvents = listener.events.filter((e) => e.asyncStart?.data.type === "route");
expect(routeEvents.length).toBe(1);
} finally {
listener.cleanup();
}
});

it("does not double-wrap handlers across repeated ~findRoute calls", async () => {
const listener = createTracingListener();
const { H3Core } = await import("../src/h3.ts");
const { tracingPlugin } = await import("../src/tracing.ts");
const { H3Event } = await import("../src/event.ts");

try {
const app = new H3Core();
const routeHandler = () => "ok";

// Cached route object returned from every ~findRoute call — mirrors a
// framework that memoizes resolved routes.
const cachedRoute = {
data: {
method: "GET" as const,
route: "/cached",
handler: routeHandler,
},
params: {},
};
app["~findRoute"] = () => cachedRoute;

tracingPlugin()(app as any);

const run = async () => {
const request = new Request("http://localhost/cached", { method: "GET" });
const event = new H3Event(request, undefined, app as any);
await app.handler(event);
};

await run();
await run();
await run();

await new Promise((resolve) => setTimeout(resolve, 10));

const routeAsyncStarts = listener.events.filter((e) => e.asyncStart?.data.type === "route");
// Exactly one route trace per request — no double-wrapping.
expect(routeAsyncStarts.length).toBe(3);
} finally {
listener.cleanup();
}
});
});
Loading