Files
speckle-server/packages/server/observability/components/httpServer/httpServerMonitoring.ts
T
Iain Sproat 5e4a6c5635 fix(server/prometheus): ensure consistent Prometheus registry is used (#4106)
* fix(server/prometheus): ensure consistent Prometheus registry is used
- there was a conflicting dependency between Metrics initialization and Modules initialization; resolved by separating registry initialization from metrics initialization
- pass in the registry to prevent implicit dependency being broken
- when registering a metric, first attempt to remove any of existing metrics with same name to prevent errors
- to prevent sneaky uses of the implicit registry, replace default import with explicit import so it is clearer when prometheusClient.registry is used

* Add tests for registering metrics
2025-03-04 08:41:53 +00:00

33 lines
1.0 KiB
TypeScript

/* istanbul ignore file */
import type { Nullable } from '@speckle/shared'
import { Registry, Gauge } from 'prom-client'
import type { Server } from 'http'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let metricActiveConnections: Nullable<Gauge<any>> = null
export const monitorActiveConnections = (params: {
httpServer: Server
registers: Registry[]
}) => {
const { httpServer, registers } = params
if (metricActiveConnections !== null) {
registers.forEach((r) => r.removeSingleMetric('speckle_server_active_connections'))
}
metricActiveConnections = new Gauge({
name: 'speckle_server_active_connections',
help: 'Number of active http connections',
async collect() {
let connectionCount = await new Promise<number>((resolve) => {
httpServer.getConnections(function (error, count) {
if (error) resolve(-1)
else resolve(count)
})
})
if (isNaN(connectionCount)) connectionCount = -1
this.set(connectionCount)
}
})
}