Skip to content

Commit

Permalink
[faucet] add user-agent header for incoming requests (#20525)
Browse files Browse the repository at this point in the history
## Description 

This PR adds the `user-agent` header for the faucet requests to keep
track which requests come from where.
The CLI gets updated to make usage of this header when requesting a
token via `sui client faucet`.

## Test plan 

Locally, fired up a grafana dashboard and also looked at the prometheus
metrics.
`total_requests_received{path="/v1/gas",user_agent="sui/1.39.0"} 1`

---

## Release notes

Check each box that your changes affect. If none of the boxes relate to
your changes, release notes aren't required.

For each box you select, include information after the relevant heading
that describes the impact of your changes that a user might notice and
any actions they must take to implement updates.

- [ ] Protocol: 
- [ ] Nodes (Validators and Full nodes): 
- [ ] Indexer: 
- [ ] JSON-RPC: 
- [ ] GraphQL: 
- [ ] CLI: 
- [ ] Rust SDK:
- [ ] REST API:
  • Loading branch information
stefan-mysten authored Dec 5, 2024
1 parent 13b6554 commit 498e4da
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 17 deletions.
14 changes: 7 additions & 7 deletions crates/sui-faucet/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,50 +45,50 @@ impl RequestMetrics {
total_requests_received: register_int_counter_vec_with_registry!(
"total_requests_received",
"Total number of requests received in Faucet",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
total_requests_succeeded: register_int_counter_vec_with_registry!(
"total_requests_succeeded",
"Total number of requests processed successfully in Faucet",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
total_requests_shed: register_int_counter_vec_with_registry!(
"total_requests_shed",
"Total number of requests that were dropped because the service was saturated",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
total_requests_failed: register_int_counter_vec_with_registry!(
"total_requests_failed",
"Total number of requests that started but failed with an uncaught error",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
total_requests_disconnected: register_int_counter_vec_with_registry!(
"total_requests_disconnected",
"Total number of requests where the client disconnected before the service \
returned a response",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
current_requests_in_flight: register_int_gauge_vec_with_registry!(
"current_requests_in_flight",
"Current number of requests being processed in Faucet",
&["path"],
&["path", "user_agent"],
registry,
)
.unwrap(),
process_latency: register_histogram_vec_with_registry!(
"process_latency",
"Latency of processing a Faucet request",
&["path"],
&["path", "user_agent"],
LATENCY_SEC_BUCKETS.to_vec(),
registry,
)
Expand Down
25 changes: 16 additions & 9 deletions crates/sui-faucet/src/metrics_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ struct MetricsGuard {
timer: Option<HistogramTimer>,
metrics: Arc<RequestMetrics>,
path: String,
user_agent: String,
}

impl RequestMetricsLayer {
Expand Down Expand Up @@ -76,7 +77,11 @@ where

fn call(&mut self, req: Request<Body>) -> Self::Future {
let path = req.uri().path().to_string();
let metrics = MetricsGuard::new(self.metrics.clone(), &path);
let user_agent = req
.headers()
.get(http::header::USER_AGENT)
.and_then(|val| val.to_str().ok());
let metrics = MetricsGuard::new(self.metrics.clone(), &path, user_agent);
let inner = self.inner.clone();

let future = Box::pin(async move {
Expand Down Expand Up @@ -113,30 +118,32 @@ impl<Res> Future for RequestMetricsFuture<Res> {
}

impl MetricsGuard {
fn new(metrics: Arc<RequestMetrics>, path: &str) -> Option<Self> {
fn new(metrics: Arc<RequestMetrics>, path: &str, user_agent: Option<&str>) -> Option<Self> {
let normalized_path = normalize_path(path);
let user_agent = user_agent.unwrap_or("unknown");

if !is_path_tracked(normalized_path) {
return None;
}

metrics
.total_requests_received
.with_label_values(&[normalized_path])
.with_label_values(&[normalized_path, user_agent])
.inc();
metrics
.current_requests_in_flight
.with_label_values(&[normalized_path])
.with_label_values(&[normalized_path, user_agent])
.inc();
Some(MetricsGuard {
timer: Some(
metrics
.process_latency
.with_label_values(&[normalized_path])
.with_label_values(&[normalized_path, user_agent])
.start_timer(),
),
metrics,
path: normalized_path.to_string(),
user_agent: user_agent.to_string(),
})
}

Expand All @@ -145,7 +152,7 @@ impl MetricsGuard {
let elapsed = timer.stop_and_record();
self.metrics
.total_requests_succeeded
.with_label_values(&[&self.path])
.with_label_values(&[&self.path, &self.user_agent])
.inc();
info!(
"Request succeeded for path {} in {:.2}s",
Expand All @@ -159,7 +166,7 @@ impl MetricsGuard {
let elapsed = timer.stop_and_record();
self.metrics
.total_requests_failed
.with_label_values(&[&self.path])
.with_label_values(&[&self.path, &self.user_agent])
.inc();

if let Some(err) = error {
Expand All @@ -183,7 +190,7 @@ impl MetricsGuard {
let elapsed = timer.stop_and_record();
self.metrics
.total_requests_shed
.with_label_values(&[&self.path])
.with_label_values(&[&self.path, &self.user_agent])
.inc();
info!("Request shed for path {} in {:.2}s", self.path, elapsed);
}
Expand All @@ -207,7 +214,7 @@ impl Drop for MetricsGuard {
let elapsed = timer.stop_and_record();
self.metrics
.total_requests_disconnected
.with_label_values(&[&self.path])
.with_label_values(&[&self.path, &self.user_agent])
.inc();
info!(
"Request disconnected for path {} in {:.2}s",
Expand Down
5 changes: 4 additions & 1 deletion crates/sui/src/client_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ use tracing::{debug, info};
#[cfg(test)]
mod profiler_tests;

static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);

/// Only to be used within CLI
pub const GAS_SAFE_OVERHEAD: u64 = 1000;

Expand Down Expand Up @@ -2552,7 +2554,8 @@ pub async fn request_tokens_from_faucet(
let client = reqwest::Client::new();
let resp = client
.post(&url)
.header("Content-Type", "application/json")
.header(http::header::CONTENT_TYPE, "application/json")
.header(http::header::USER_AGENT, USER_AGENT)
.json(&json_body)
.send()
.await?;
Expand Down

0 comments on commit 498e4da

Please sign in to comment.