43 lines
1.6 KiB
TypeScript
43 lines
1.6 KiB
TypeScript
/**
|
|
* Token-protected `/api/metrics` resource route. Same auth/contract as the
|
|
* api app's /metrics endpoint so a single Prometheus job can be reused.
|
|
*/
|
|
import { isMetricsEnabled, validateMetricsTokenAuth } from "@hivegrid/metrics";
|
|
import type { LoaderFunctionArgs } from "react-router";
|
|
import { getWebMetrics } from "~/lib/metrics/registry";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
|
|
export async function loader({ request }: LoaderFunctionArgs): Promise<Response> {
|
|
const { t } = await getTranslations(request);
|
|
const enabled = isMetricsEnabled(process.env);
|
|
if (!enabled) {
|
|
return Response.json({ error: { code: "not_found", message: t("api.errors.metricsEndpointNotEnabled") } }, { status: 404 });
|
|
}
|
|
|
|
const auth = validateMetricsTokenAuth({
|
|
metricsEnabled: true,
|
|
configuredToken: process.env.METRICS_TOKEN,
|
|
authorizationHeader: request.headers.get("authorization"),
|
|
});
|
|
|
|
if (!auth.ok) {
|
|
if (auth.status === 500) {
|
|
return Response.json({ error: { code: "token_misconfigured", message: t("api.errors.metricsTokenNotConfigured") } }, { status: 500 });
|
|
}
|
|
if (auth.status === 403) {
|
|
return Response.json({ error: { code: "not_found", message: t("api.errors.metricsEndpointNotEnabled") } }, { status: 404 });
|
|
}
|
|
return Response.json({ error: { code: auth.code, message: t("api.errors.authenticationRequired") } }, { status: 401 });
|
|
}
|
|
|
|
const { registry } = getWebMetrics();
|
|
const body = await registry.metrics();
|
|
return new Response(body, {
|
|
status: 200,
|
|
headers: {
|
|
"content-type": registry.contentType,
|
|
"cache-control": "no-store",
|
|
},
|
|
});
|
|
}
|