Skip to content

feat: add prometheus metrics and integration tests to rpc-extractor - #339

Merged
0xB10C merged 3 commits into
peer-observer:masterfrom
GuiSchet:fetch-errors-via-prometheus
Mar 9, 2026
Merged

0xB10C merged 3 commits into
peer-observer:masterfrom
GuiSchet:fetch-errors-via-prometheus

Conversation

@GuiSchet

Copy link
Copy Markdown
Contributor

PR Description:

Summary

This PR implements Prometheus metrics for the rpc-extractor and adds a robust suite of integration tests.

Key Changes

Metrics Instrumentation: Added Prometheus metrics to track RPC fetch durations and error rates (both for RPC calls and NATS publishing).
Configuration: Introduced a new --prometheus-address CLI argument (defaulting to 0.0.0.0:8284) to serve the metrics.
Enhanced Testing:
- Added unit tests for the metrics registration and logic.
- Implemented 14 integration tests.
- Verified that all enabled RPC methods (e.g., getpeerinfo, getmempoolinfo, uptime, etc.) correctly publish events.
- Verified that Prometheus correctly records durations and increments error counters on failures (unreachable host, invalid auth).

Related Issues

#201

Comment thread extractors/rpc/tests/integration.rs Resolved
Comment thread extractors/rpc/tests/integration.rs Resolved
@GuiSchet

Copy link
Copy Markdown
Contributor Author

Changes:

  • Refactored metrics from lazy_static! globals to a Metrics struct with per-instance Registry (similar to
    tools/metrics/src/metrics.rs)
  • Moved metrics integration tests to separate metrics_integration.rs file
  • Removed #[serial] annotations - tests now run in parallel
  • Removed serial_test dev-dependency

Comment thread extractors/rpc/src/lib.rs Outdated
Comment on lines +148 to +150
// Start the metric server with our custom registry.
shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone()))
.expect("Could not start metric server");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should return a RuntimeError. You are going to need to implement it similar to the io:Error in

Suggested change
// Start the metric server with our custom registry.
shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone()))
.expect("Could not start metric server");
// Start the metric server with our custom registry.
shared::metricserver::start(&args.prometheus_address, Some(metrics.registry.clone()))?;

Comment thread extractors/rpc/src/lib.rs Outdated
Comment on lines +289 to +292
let _timer = metrics
.rpc_fetch_duration
.with_label_values(&[method_name])
.start_timer();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I it might work without it, as the duration is recorded when the timer is dropped. However, would be good to be explicit about only recording the duration for successful fetches?

Comment thread extractors/rpc/src/lib.rs Outdated
.with_label_values(&[method_name])
.start_timer();
let res = f();
if res.is_err() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread extractors/rpc/Cargo.toml Outdated
Comment on lines +9 to +11
[dev-dependencies]
ureq = "2.9"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An alternative would be to reuse this:

fn fetch_metrics(port: u16) -> Result<String, std::io::Error> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are no longer any dev-dependencies, so this can be removed?

@0xB10C 0xB10C left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a few comments above. General direction looks good!

Any reason this is a draft?

@GuiSchet

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I had some initial doubts about the tests, that's why I left it as a draft. I'll review your latest observations today.

@GuiSchet
GuiSchet marked this pull request as ready for review January 21, 2026 19:05
@GuiSchet
GuiSchet force-pushed the fetch-errors-via-prometheus branch from bd5d90c to 474819d Compare February 3, 2026 17:46
@0xB10C

0xB10C commented Feb 3, 2026

Copy link
Copy Markdown
Collaborator

I'll have another look at this soon. I want to finish #344 first.

@0xB10C 0xB10C linked an issue Feb 6, 2026 that may be closed by this pull request
@0xB10C

0xB10C commented Feb 6, 2026

Copy link
Copy Markdown
Collaborator

Ok, this is next! Can you rebase? Also, can you squash the commits into a few logically separate ones? No need to have seperate fixups for formatting in a PR :) Thanks!

@GuiSchet
GuiSchet force-pushed the fetch-errors-via-prometheus branch from f96fef0 to 1f5cc1f Compare February 9, 2026 18:03
@GuiSchet

GuiSchet commented Feb 9, 2026

Copy link
Copy Markdown
Contributor Author

Sorry for the commit spam and multiple rebases, I was testing things out. Done & squashed the commits too.

Comment thread extractors/rpc/Cargo.toml Outdated
Comment on lines +9 to +11
[dev-dependencies]
ureq = "2.9"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are no longer any dev-dependencies, so this can be removed?

Comment thread extractors/rpc/src/lib.rs Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason this is not instrumented?

Comment thread extractors/rpc/src/lib.rs Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here also not instrumented?

Comment thread extractors/rpc/src/lib.rs
})?;
Ok(())
}

@deadmanoz deadmanoz Feb 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Below 2 methods as per other comments (that is, not instrumented).

Comment thread shared/src/testing/metrics_fetcher.rs Outdated
fetch_metrics(port, "/")
}

/// Extracts the count value from a histogram metric.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there much difference between these 2 methods?

one uses starts_with, the other uses contains

Seems like we could consolidate into a single method?

Comment thread shared/src/testing/metrics_fetcher.rs Outdated
/// # Panics
/// Panics if the metric is not found or the value cannot be parsed.
pub fn get_histogram_count(metrics_raw: &str, metric_name: &str, label_value: &str) -> u64 {
let search_pattern = format!("{}{{rpc_method=\"{}\"}}", metric_name, label_value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are only usable for RPC-extractor specific code with rpc_method

Comment thread shared/src/testing/metrics_fetcher.rs Outdated
/// # Panics
/// Panics if the metric is not found or the value cannot be parsed.
pub fn get_counter_value(metrics_raw: &str, metric_name: &str, label_value: &str) -> u64 {
let search_pattern = format!("{}{{rpc_method=\"{}\"}}", metric_name, label_value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are only usable for RPC-extractor specific code with rpc_method

Comment on lines +89 to +114
fn setup_node(conf: corepc_node::Conf) -> corepc_node::Node {
info!("env BITCOIND_EXE={:?}", std::env::var("BITCOIND_EXE"));
info!("exe_path={:?}", corepc_node::exe_path());

if let Ok(exe_path) = corepc_node::exe_path() {
info!("Using bitcoind at '{}'", exe_path);
return corepc_node::Node::with_conf(exe_path, &conf).unwrap();
}

info!("Trying to download a bitcoind..");
corepc_node::Node::from_downloaded_with_conf(&conf).unwrap()
}

fn setup_two_connected_nodes() -> (corepc_node::Node, corepc_node::Node) {
// node1 listens for p2p connections
let mut node1_conf = corepc_node::Conf::default();
node1_conf.p2p = corepc_node::P2P::Yes;
let node1 = setup_node(node1_conf);

// node2 connects to node1
let mut node2_conf = corepc_node::Conf::default();
node2_conf.p2p = node1.p2p_connect(true).unwrap();
let node2 = setup_node(node2_conf);

(node1, node2)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be duplicate with the code in integration.rs? How about having a lib.rs for this?

Comment on lines +44 to +62
#[allow(clippy::too_many_arguments)]
fn make_test_args(
nats_port: u16,
rpc_url: String,
cookie_file: String,
prometheus_address: String,
disable_getpeerinfo: bool,
disable_getmempoolinfo: bool,
disable_uptime: bool,
disable_getnettotals: bool,
disable_getmemoryinfo: bool,
disable_getaddrmaninfo: bool,
disable_getchaintxstats: bool,
disable_getnetworkinfo: bool,
disable_getblockchaininfo: bool,
disable_getorphantxs: bool,
disable_getrawaddrman: bool,
) -> Args {
Args::new(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the function from integration.rs and use EnabledRPCsInTest in the tests.

EnabledRPCsInTest {
getmempoolinfo: true,
..Default::default()
},

Comment thread extractors/rpc/src/lib.rs Outdated
pub query_interval_less_frequent: u64,

/// Address to serve Prometheus metrics on.
#[arg(long, default_value = "0.0.0.0:8284")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't bind to all interfaces by default: 127.0.0.1:8284

Comment thread extractors/rpc/src/metrics.rs Outdated
Comment on lines +95 to +107
#[test]
fn test_metric_registration() {
// Creating a new Metrics instance should not panic.
// This verifies that the metrics are registered correctly with the custom registry.
let metrics = Metrics::new();
let _ = metrics
.rpc_fetch_duration
.with_label_values(&["test_method"]);
let _ = metrics.rpc_fetch_errors.with_label_values(&["test_method"]);
let _ = metrics
.nats_publish_errors
.with_label_values(&["test_method"]);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this test mainly tests functionallity of the prometheus crate and not our code. Not sure if needed.

Comment thread extractors/rpc/src/metrics.rs Outdated
Comment on lines +109 to +119
#[test]
fn test_valid_label_values() {
// Verify that all RPC method names are valid labels.
// Invalid labels would cause a panic when accessing with_label_values().
let metrics = Metrics::new();
for method in RPC_METHODS {
let _ = metrics.rpc_fetch_duration.with_label_values(&[method]);
let _ = metrics.rpc_fetch_errors.with_label_values(&[method]);
let _ = metrics.nats_publish_errors.with_label_values(&[method]);
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. RPC_METHODS is missing methods. And we'll forget adding new ones to the list.
  2. I don't think this test is worthwhile having. Again, we are testing functionallity provided by an upstream create here.

Feel free to drop

Comment thread extractors/rpc/src/metrics.rs Outdated
Comment on lines +121 to +140
#[test]
fn test_histogram_timer() {
// Verify that the histogram timer records observations.
let metrics = Metrics::new();
let method = "test_histogram_timer";
let histogram = metrics.rpc_fetch_duration.with_label_values(&[method]);
let count_before = histogram.get_sample_count();

{
let _timer = histogram.start_timer();
// Timer is dropped here, recording the observation
}

let count_after = histogram.get_sample_count();
assert_eq!(
count_after,
count_before + 1,
"Histogram should have recorded one observation"
);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again, this is not testing our code

Comment thread extractors/rpc/src/metrics.rs Outdated
Comment on lines +78 to +81
#[cfg(test)]
mod tests {
use super::*;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can drop all of these as they aren't testing our code but the upstream code.

Since we have intregration test coverage for our metrics, I think there is no need to test the functionallity of the prometheus crate here. We'll notice if something changes in a way we don't like through the integration tests

@0xB10C
0xB10C marked this pull request as draft February 12, 2026 09:31
@GuiSchet
GuiSchet force-pushed the fetch-errors-via-prometheus branch from 1f5cc1f to 1ca6190 Compare February 15, 2026 18:25
@GuiSchet

Copy link
Copy Markdown
Contributor Author

Thanks for the review, I think that all has been addressed:

  • Per-instance Metrics struct with custom registry (parallel tests).
  • All 11 RPC methods instrumented with measure_rpc_call + NATS publish error tracking.
  • Generic get_metric_value in shared/src/testing/metrics_fetcher.rs.
  • Shared test helpers in tests/common/mod.rs.
  • Dropped unit tests that only tested upstream prometheus crate...
  • Removed empty [dev-dependencies], default address 127.0.0.1:8284, ? propagation.

@GuiSchet
GuiSchet marked this pull request as ready for review February 18, 2026 20:30

@deadmanoz deadmanoz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Almost there, just a few more things to consider/address!

};

#[tokio::test]
async fn test_integration_metrics_server_basic() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please provide a brief comment for each test describing what it does/what it's purpose is?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e.g. the sequence that happens within

}

#[derive(Default)]
pub struct EnabledRPCsInTest {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not know...

#[derive(Default)] on a struct with bool fields gives each field false by default!

node1.rpc_url().replace("http://", ""),
node1.params.cookie_file.display().to_string(),
format!("127.0.0.1:{}", metrics_port),
EnabledRPCsInTest {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you do the impl block with all() and enabled_methods(), we simply just use EnabledRPCsInTest::all() here!!!

pub getorphantxs: bool,
pub getrawaddrman: bool,
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should add the following here:

  impl EnabledRPCsInTest {
      pub fn all() -> Self {
          Self {
              getpeerinfo: true,
              getmempoolinfo: true,
              uptime: true,
              getnettotals: true,
              getmemoryinfo: true,
              getaddrmaninfo: true,
              getchaintxstats: true,
              getnetworkinfo: true,
              getblockchaininfo: true,
              getorphantxs: true,
              getrawaddrman: true,
          }
      }

      pub fn enabled_methods(&self) -> Vec<&'static str> {
          let mut methods = Vec::new();
          if self.getpeerinfo { methods.push("getpeerinfo"); }
          if self.getmempoolinfo { methods.push("getmempoolinfo"); }
          if self.uptime { methods.push("uptime"); }
          if self.getnettotals { methods.push("getnettotals"); }
          if self.getmemoryinfo { methods.push("getmemoryinfo"); }
          if self.getaddrmaninfo { methods.push("getaddrmaninfo"); }
          if self.getchaintxstats { methods.push("getchaintxstats"); }
          if self.getnetworkinfo { methods.push("getnetworkinfo"); }
          if self.getblockchaininfo { methods.push("getblockchaininfo"); }
          if self.getorphantxs { methods.push("getorphantxs"); }
          if self.getrawaddrman { methods.push("getrawaddrman"); }
          methods
      }
  }

This would mean that one place needs updating as new RPCs are added. We don't need to update the tests too, they get it by virtue of using EnabledRPCsInTest::all() and EnabledRPCsInTest::enabled_methods()`!!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll definitely try this!

let metrics = fetch_metrics(metrics_port, "/metrics").expect("Should fetch metrics");

// Verify that each enabled RPC method has recorded at least one call
let methods_to_check = [

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this whole section, simply becomes...

let rpcs = EnabledRPCsInTest::all();

for method in rpcs.enabled_methods() {
    let count = get_metric_value(/* ... */);
    assert!(count >= 1, /* ... */);
}

}

/// Convenience wrapper that fetches from the root path "/".
pub fn fetch_metrics_root(port: u16) -> Result<String, std::io::Error> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So in shared/src/metricserver.rs handle_request actually discards the path!

Server reads raw bytes into buffer, but no inspection of method/path/headers:

fn handle_request(
    mut stream: TcpStream,
    registry: Option<Registry>,
) -> Result<(), RequestHandlingError> {
    let mut buffer = [0; 1024];
    let _ = stream.read(&mut buffer)?;
...

Server always executes the same response path:

  • Gathers metrics (reg.gather() / prometheus::gather())
  • Encodes to text
  • Writes fixed HTTP/1.1 200 OK with the metrics body
  • No branch on request path exists anywhere in handle_request.

I don't think this was intentional with the original implementation (to confirm with @0xB10C?), but it means that fetch_metrics_root is redundant..

@0xB10C 0xB10C Mar 2, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did that on purpose. It just serves metrics on all paths. On /, /metrics, /abc, all should return the same thing. I don't want to parse the path in there.

That said, probably a comment about this would have helped to explain it :)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for clarification @0xB10C.

So yeah I think fetch_metrics_root is redundant, can just use fetch_metrics(port, "/") (or similar) everywhere.

@GuiSchet
GuiSchet force-pushed the fetch-errors-via-prometheus branch from 1ca6190 to abb08fb Compare March 5, 2026 18:00
@GuiSchet

GuiSchet commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks again @deadmanoz !

Added impl EnabledRPCsInTest with all(), added #[allow(dead_code)] too, because it's referenced only in integration tests.
Added doc comments to all test.
Refactored to use EnabledRPCsInTest::all() and rpcs.enabled_methods() instead of the hardcoded struct.
shared/src/metricserver.rs: Added a comment before stream.read clarifying that the HTTP method/path/headers are intentionally ignored.

@deadmanoz

Copy link
Copy Markdown
Collaborator

I will review again

@deadmanoz

Copy link
Copy Markdown
Collaborator

Nice, thanks @GuiSchet. I think the only thing that remains is the redundant fetch_metrics_root, have left a comment. It's not blocking but maybe is worth tightening

Comment thread Cargo.lock
Comment on lines 266 to +1295
@@ -403,11 +403,12 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"

[[package]]
name = "colored"
version = "3.1.1"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8"
dependencies = [
"windows-sys 0.61.2",
"lazy_static",
"windows-sys 0.48.0",
]

[[package]]
@@ -1175,9 +1176,9 @@ dependencies = [

[[package]]
name = "log"
version = "0.4.29"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"

[[package]]
name = "log-extractor"
@@ -1289,9 +1290,9 @@ dependencies = [

[[package]]
name = "once_cell"
version = "1.18.0"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These look like unrelated updates to me?

@0xB10C
0xB10C merged commit f16c1e7 into peer-observer:master Mar 9, 2026
12 checks passed
@0xB10C

0xB10C commented Mar 9, 2026 •

Copy link
Copy Markdown
Collaborator

Thank you @GuiSchet!

I tested this a bit locally and it looks good.

For the new prometheus metrics endpoint, a next step would be to support it in the infrastructure. I opened peer-observer/infra-library#107 for it. Feel free to focus on the alerts too for now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rpc-extractor: offer RPC fetch timings and errors via a prometheus server

3 participants