75 lines
2.5 KiB
TypeScript
75 lines
2.5 KiB
TypeScript
/**
|
|
* `withMetrics(routeId, loader)` — wraps a React Router v7 SSR loader so each
|
|
* invocation observes `web_ssr_loader_duration_seconds_bucket{route, status}`.
|
|
*
|
|
* Apply it to the **highest-traffic** loaders only (root, dashboard, login,
|
|
* tenant index, etc.) — wrapping every loader would multiply boilerplate
|
|
* without paying off in extra signal. Operators can extend coverage later if
|
|
* we identify hotspots.
|
|
*
|
|
* Self-noop when `METRICS_ENABLED=false` so dev runs stay zero-overhead.
|
|
*/
|
|
import { isMetricsEnabled } from "@toolctrl/metrics";
|
|
import { getWebMetrics } from "./registry.js";
|
|
|
|
type AnyLoaderArgs = {
|
|
request?: Request;
|
|
params?: Record<string, string | undefined>;
|
|
context?: unknown;
|
|
};
|
|
|
|
export type SsrLoader<TArgs extends AnyLoaderArgs = AnyLoaderArgs, TResult = unknown> = (args: TArgs) => Promise<TResult> | TResult;
|
|
|
|
export type WithMetricsOptions = {
|
|
/** Override the time source — tests inject a deterministic clock. */
|
|
now?: () => number;
|
|
/** Override the `METRICS_ENABLED` check — tests force enabled=true. */
|
|
enabledOverride?: boolean;
|
|
};
|
|
|
|
export function withMetrics<TArgs extends AnyLoaderArgs, TResult>(
|
|
routeId: string,
|
|
loader: SsrLoader<TArgs, TResult>,
|
|
options: WithMetricsOptions = {},
|
|
): SsrLoader<TArgs, TResult> {
|
|
return async function wrappedLoader(args: TArgs): Promise<TResult> {
|
|
const enabled = options.enabledOverride ?? isMetricsEnabled(process.env);
|
|
if (!enabled) {
|
|
return loader(args);
|
|
}
|
|
const now = options.now ?? (() => performance.now());
|
|
const started = now();
|
|
let status: "ok" | "error" | "redirect" = "ok";
|
|
try {
|
|
const result = await loader(args);
|
|
status = classifyStatus(result);
|
|
return result;
|
|
} catch (error) {
|
|
status = "error";
|
|
throw error;
|
|
} finally {
|
|
const elapsedSeconds = (now() - started) / 1000;
|
|
try {
|
|
getWebMetrics().metrics.webSsrLoaderDurationSeconds.labels({ route: routeId, status }).observe(elapsedSeconds);
|
|
} catch {
|
|
// Metric writes never break loader execution.
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Inspects the loader return value for a Response that signals redirect /
|
|
* client error. React Router treats thrown Response objects as the loader's
|
|
* error path (handled in catch block), so anything returned here counts as
|
|
* "ok" unless the status is a redirect.
|
|
*/
|
|
function classifyStatus(result: unknown): "ok" | "redirect" {
|
|
if (result instanceof Response) {
|
|
if (result.status >= 300 && result.status < 400) {
|
|
return "redirect";
|
|
}
|
|
}
|
|
return "ok";
|
|
}
|