refactor metrics, fix deps

This commit is contained in:
wphan
2025-07-15 11:56:56 -07:00
parent d19e33e840
commit 74eb54c164
13 changed files with 2278 additions and 2924 deletions

View File

@@ -1,15 +1,20 @@
import { Request, Response } from 'express';
import responseTime = require('response-time');
import {
endpointResponseTimeHistogram,
responseStatusCounter,
} from './metrics';
import { MEASURED_ENDPOINTS } from '../utils/constants';
import { SlotSource } from '@drift-labs/sdk';
import {
evaluateHealth,
globalHealthState,
setHealthStatus,
HEALTH_STATUS,
} from './healthCheck';
import { logger } from '../utils/logger';
import { GaugeValue } from './metricsV2';
export const handleResponseTime = (
measuredEndpoints: string[] = MEASURED_ENDPOINTS
) => {
return responseTime((req: Request, res: Response, time: number) => {
return responseTime((req: Request, _res: Response, _time: number) => {
const endpoint = req.path;
if (!measuredEndpoints.includes(endpoint)) {
@@ -19,14 +24,60 @@ export const handleResponseTime = (
// return;
//}
responseStatusCounter.add(1, {
endpoint,
status: res.statusCode,
});
// TODO: add these back if want to profile response times
const responseTimeMs = time;
endpointResponseTimeHistogram.record(responseTimeMs, {
endpoint,
});
// responseStatusCounter.add(1, {
// endpoint,
// status: res.statusCode,
// });
// const responseTimeMs = time;
// endpointResponseTimeHistogram.record(responseTimeMs, {
// endpoint,
// });
});
};
/**
* Middleware that checks the health of the slot subscriber.
* Health is determined by:
* 1. Regular slot updates
* 2. Minimum slot update rate
*/
export const handleHealthCheck = (
slotSource: SlotSource,
healthCheckGauge?: GaugeValue
) => {
return async (_req, res, _next) => {
const currentSlot = slotSource.getSlot();
const { isHealthy, reason } = evaluateHealth(currentSlot);
if (!isHealthy) {
logger.error(
`Unhealthy: ${reason}, ` +
`Details: currentSlot=${currentSlot}, ` +
`lastSlot=${globalHealthState.lastSlot}, ` +
`timeSinceLastSlot=${
Date.now() - globalHealthState.lastSlotTimestamp
}ms`
);
if (healthCheckGauge) {
healthCheckGauge.setLatestValue(
Number(HEALTH_STATUS.UnhealthySlotSubscriber),
{}
);
}
setHealthStatus(HEALTH_STATUS.UnhealthySlotSubscriber);
res.writeHead(500);
res.end('NOK');
return;
}
if (healthCheckGauge) {
healthCheckGauge.setLatestValue(Number(HEALTH_STATUS.Ok), {});
}
setHealthStatus(HEALTH_STATUS.Ok);
res.writeHead(200);
res.end('OK');
};
};