import { describe, it, expect, beforeEach } from "vitest"; import { resetWebMetricsForTests, getWebMetrics } from "./registry.js"; import { withMetrics } from "./ssr.js"; beforeEach(() => { resetWebMetricsForTests(); }); describe("withMetrics", () => { it("passes through and is a no-op when metrics are disabled", async () => { const loader = withMetrics("root", async () => "value", { enabledOverride: false }); expect(await loader({})).toBe("value"); const text = await getWebMetrics().registry.metrics(); expect(text).not.toContain('web_ssr_loader_duration_seconds_count{route="root"'); }); it("observes loader latency with route + status=ok", async () => { let t = 0; const loader = withMetrics( "dashboard", async () => ({ ok: true }), { enabledOverride: true, now: () => { const next = t; t += 80; // 80ms — should hit the 0.1 bucket return next; }, }, ); await loader({}); const text = await getWebMetrics().registry.metrics(); expect(text).toMatch(/web_ssr_loader_duration_seconds_count\{[^}]*route="dashboard"[^}]*status="ok"[^}]*\} 1/); expect(text).toMatch(/web_ssr_loader_duration_seconds_bucket\{le="0.1",[^}]*route="dashboard"[^}]*status="ok"[^}]*\} 1/); }); it("labels redirect responses as status=redirect", async () => { const loader = withMetrics( "login", async () => new Response(null, { status: 302, headers: { location: "/dashboard" } }), { enabledOverride: true }, ); await loader({}); const text = await getWebMetrics().registry.metrics(); expect(text).toMatch(/web_ssr_loader_duration_seconds_count\{[^}]*route="login"[^}]*status="redirect"[^}]*\} 1/); }); it("labels thrown loaders as status=error and re-throws", async () => { const loader = withMetrics( "fail", async () => { throw new Error("boom"); }, { enabledOverride: true }, ); await expect(loader({})).rejects.toThrow("boom"); const text = await getWebMetrics().registry.metrics(); expect(text).toMatch(/web_ssr_loader_duration_seconds_count\{[^}]*route="fail"[^}]*status="error"[^}]*\} 1/); }); });