From e3533efe796ef84fcc672553a515dfa418118678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20C=C3=A1rdenas?= Date: Tue, 2 Jul 2024 08:57:31 -0600 Subject: [PATCH] fix: enable prometheus metrics (#7) --- api/src/index.ts | 34 +++++++++++++++++++--------------- api/src/metrics/metrics.ts | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 15 deletions(-) create mode 100644 api/src/metrics/metrics.ts diff --git a/api/src/index.ts b/api/src/index.ts index 33592ba..eaeb6b8 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -1,8 +1,13 @@ -import { isProdEnv, logger, registerShutdownConfig } from '@hirosystems/api-toolkit'; +import { + buildPrometheusServer, + isProdEnv, + logger, + registerShutdownConfig, +} from '@hirosystems/api-toolkit'; import { buildApiServer } from './api/init'; import { ENV } from './env'; import { PgStore } from './pg/pg-store'; -// import { ApiMetrics } from './metrics/metrics'; +import { ApiMetrics } from './metrics/metrics'; async function initApiService(db: PgStore) { logger.info('Initializing API service...'); @@ -17,19 +22,18 @@ async function initApiService(db: PgStore) { await fastify.listen({ host: ENV.API_HOST, port: ENV.API_PORT }); - // if (isProdEnv) { - // const promServer = await buildPromServer({ metrics: fastify.metrics }); - // registerShutdownConfig({ - // name: 'Prometheus Server', - // forceKillable: false, - // handler: async () => { - // await promServer.close(); - // }, - // }); - - // // ApiMetrics.configure(db); - // await promServer.listen({ host: ENV.API_HOST, port: 9153 }); - // } + if (isProdEnv) { + const promServer = await buildPrometheusServer({ metrics: fastify.metrics }); + registerShutdownConfig({ + name: 'Prometheus Server', + forceKillable: false, + handler: async () => { + await promServer.close(); + }, + }); + ApiMetrics.configure(db); + await promServer.listen({ host: ENV.API_HOST, port: 9153 }); + } } async function initApp() { diff --git a/api/src/metrics/metrics.ts b/api/src/metrics/metrics.ts new file mode 100644 index 0000000..d7850ad --- /dev/null +++ b/api/src/metrics/metrics.ts @@ -0,0 +1,22 @@ +import * as prom from 'prom-client'; +import { PgStore } from '../pg/pg-store'; + +export class ApiMetrics { + /** The most recent Bitcoin block height ingested by the API */ + readonly runes_api_block_height: prom.Gauge; + + static configure(db: PgStore): ApiMetrics { + return new ApiMetrics(db); + } + + private constructor(db: PgStore) { + this.runes_api_block_height = new prom.Gauge({ + name: `runes_api_block_height`, + help: 'The most recent Bitcoin block height ingested by the API', + async collect() { + const height = await db.getChainTipBlockHeight(); + this.set(parseInt(height ?? '0')); + }, + }); + } +}