Files
zeavis-edu/apps/web/vite-plugin-metrics.ts
T

43 lines
1.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Plugin } from 'vite';
/**
* Vite plugin that exposes a /metrics endpoint during development.
*
* The endpoint returns Prometheustext metrics collected in
* src/lib/telemetry.ts.
*/
export function metricsPlugin(): Plugin {
let telemetryModule: typeof import('./src/lib/telemetry') | null = null;
return {
name: 'zeavis-metrics',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
// Only handle GET /metrics
if (req.method !== 'GET' || !req.url?.startsWith('/metrics')) {
return next();
}
// Lazyload the telemetry module (ensures the app is bootstrapped first)
if (!telemetryModule) {
try {
telemetryModule = await server.ssrLoadModule('./src/lib/telemetry.ts') as typeof import('./src/lib/telemetry');
} catch {
// If the module isn't ready yet, return an empty body
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('# telemetry module not yet loaded\n');
return;
}
}
const body = telemetryModule.collectMetrics();
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(body);
});
},
};
}