From 20bf67085f8ae4697114326036f98322e4509ef9 Mon Sep 17 00:00:00 2001 From: 0xOse <0xosepatrick@gmail.com> Date: Mon, 26 Jan 2026 16:56:58 +0100 Subject: [PATCH] feat: track protocol stream open/close count in metrics Adds two new counter metrics to complement the existing gauge: - libp2p_protocol_streams_opened_total - libp2p_protocol_streams_closed_total These counters enable calculating stream open/close rates and total throughput over time, addressing the limitations of the existing gauge metric which only shows current state. Fixes #3262 --- packages/libp2p/src/connection.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/libp2p/src/connection.ts b/packages/libp2p/src/connection.ts index 6308e1e422..2dd58c6c3d 100644 --- a/packages/libp2p/src/connection.ts +++ b/packages/libp2p/src/connection.ts @@ -177,6 +177,20 @@ export class Connection extends TypedEventEmitter implement this.components.metrics?.trackProtocolStream(muxedStream) + // track stream open/close counts + const streamKey = `${muxedStream.direction} ${muxedStream.protocol ?? 'unnegotiated'}` + this.components.metrics?.registerCounterGroup('libp2p_protocol_streams_opened_total', { + label: 'protocol', + help: 'Total count of protocol streams opened' + }).increment({ [streamKey]: true }) + + muxedStream.addEventListener('close', () => { + this.components.metrics?.registerCounterGroup('libp2p_protocol_streams_closed_total', { + label: 'protocol', + help: 'Total count of protocol streams closed' + }).increment({ [streamKey]: true }) + }, { once: true }) + const middleware = this.components.registrar.getMiddleware(muxedStream.protocol) return await this.runMiddlewareChain(muxedStream, this, middleware) @@ -231,6 +245,20 @@ export class Connection extends TypedEventEmitter implement this.components.metrics?.trackProtocolStream(muxedStream) + // track stream open/close counts + const streamKey = `${muxedStream.direction} ${muxedStream.protocol ?? 'unnegotiated'}` + this.components.metrics?.registerCounterGroup('libp2p_protocol_streams_opened_total', { + label: 'protocol', + help: 'Total count of protocol streams opened' + }).increment({ [streamKey]: true }) + + muxedStream.addEventListener('close', () => { + this.components.metrics?.registerCounterGroup('libp2p_protocol_streams_closed_total', { + label: 'protocol', + help: 'Total count of protocol streams closed' + }).increment({ [streamKey]: true }) + }, { once: true }) + const { handler, options } = this.components.registrar.getHandler(muxedStream.protocol) if (this.limits != null && options.runOnLimitedConnection !== true) {