Skip to content

Commit bde1037

Browse files
authored
feat(prometheus): add chain tip metrics (#2333)
1 parent 0ddd6a6 commit bde1037

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/datastore/pg-write-store.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as assert from 'assert';
2+
import * as prom from 'prom-client';
23
import { getOrAdd, I32_MAX, getIbdBlockHeight, getUintEnvOrDefault } from '../helpers';
34
import {
45
DbBlock,
@@ -130,6 +131,12 @@ type TransactionHeader = {
130131
export class PgWriteStore extends PgStore {
131132
readonly isEventReplay: boolean;
132133
protected isIbdBlockHeightReached = false;
134+
private metrics:
135+
| {
136+
blockHeight: prom.Gauge;
137+
burnBlockHeight: prom.Gauge;
138+
}
139+
| undefined;
133140

134141
constructor(
135142
sql: PgSqlClient,
@@ -138,6 +145,18 @@ export class PgWriteStore extends PgStore {
138145
) {
139146
super(sql, notifier);
140147
this.isEventReplay = isEventReplay;
148+
if (isProdEnv) {
149+
this.metrics = {
150+
blockHeight: new prom.Gauge({
151+
name: 'stacks_block_height',
152+
help: 'Current chain tip block height',
153+
}),
154+
burnBlockHeight: new prom.Gauge({
155+
name: 'burn_block_height',
156+
help: 'Current burn block height',
157+
}),
158+
};
159+
}
141160
}
142161

143162
static async connect({
@@ -356,7 +375,7 @@ export class PgWriteStore extends PgStore {
356375
if (!this.isEventReplay) {
357376
this.debounceMempoolStat();
358377
}
359-
if (isCanonical)
378+
if (isCanonical) {
360379
await sql`
361380
WITH new_tx_count AS (
362381
SELECT tx_count + ${data.txs.length} AS tx_count FROM chain_tip
@@ -372,6 +391,10 @@ export class PgWriteStore extends PgStore {
372391
tx_count = (SELECT tx_count FROM new_tx_count),
373392
tx_count_unanchored = (SELECT tx_count FROM new_tx_count)
374393
`;
394+
if (this.metrics) {
395+
this.metrics.blockHeight.set(data.block.block_height);
396+
}
397+
}
375398
});
376399
// Do we have an IBD height defined in ENV? If so, check if this block update reached it.
377400
const ibdHeight = getIbdBlockHeight();
@@ -1938,9 +1961,13 @@ export class PgWriteStore extends PgStore {
19381961
}
19391962

19401963
async updateBurnChainBlockHeight(args: { blockHeight: number }): Promise<void> {
1941-
await this.sql`
1964+
const result = await this.sql<{ burn_block_height: number }[]>`
19421965
UPDATE chain_tip SET burn_block_height = GREATEST(${args.blockHeight}, burn_block_height)
1966+
RETURNING burn_block_height
19431967
`;
1968+
if (this.metrics && result.length > 0) {
1969+
this.metrics.burnBlockHeight.set(result[0].burn_block_height);
1970+
}
19441971
}
19451972

19461973
async insertSlotHoldersBatch(sql: PgSqlClient, slotHolders: DbRewardSlotHolder[]): Promise<void> {

0 commit comments

Comments
 (0)