Expand description
Provides a lightweight HTTP server to expose (Prometheus) metrics.
This module runs a simple HTTP server that listens on a specified port
and serves an endpoint (/metrics) which returns a plain-text string
representation of your metrics. It can be used to expose metrics to DSH
or any Prometheus-compatible monitoring service.
§Overview
- Port: Chosen at runtime; ensure it’s exposed in your container if using Docker.
- Metrics Encoder: You supply a function that returns a
Stringrepresentation of your metrics (e.g., from a Prometheus client library). - Thread Model: The server runs on a separate Tokio task. You can optionally
keep the resulting
JoinHandleif you want to monitor or manage its lifecycle.
§Common Usage
- Define a function that gathers and encodes your metrics to a
String. - Call
start_http_serverwith the port and your metrics function. - Access your metrics at
http://<HOST>:<PORT>/metrics. - Configure your DSH or Docker environment accordingly (if needed).
§Example
use dsh_sdk::utils::metrics::start_http_server;
fn encode_metrics() -> String {
// Provide custom logic to gather and encode metrics into a string.
// Example below is a placeholder.
"my_counter 1".to_string()
}
#[tokio::main]
async fn main() {
// Launch a metrics server on port 9090
start_http_server(9090, encode_metrics);
// The server runs until the main thread stops or is aborted.
// ...
}Once running, you can query your metrics at http://localhost:9090/metrics.
§Configuration with DSH
In your Dockerfile, be sure to expose that port:
EXPOSE 9090Then, in your DSH service configuration, specify the port and path for the metrics:
"metrics": {
"port": 9090,
"path": "/metrics"
},§Monitoring the Server Task
start_http_server spawns a Tokio task which returns a JoinHandle. You can:
- Ignore it: The server continues until the main application exits.
- Await it to see if the server encounters an error or closes unexpectedly.
fn encode_metrics() -> String {
"my_metrics 1".to_string() // Dummy example
}
#[tokio::main]
async fn main() {
let server_handle = start_http_server(9090, encode_metrics);
tokio::select! {
// Some app logic or graceful shutdown condition
_ = sleep(Duration::from_secs(300)) => {
println!("Main application stopping...");
}
// If the metrics server stops unexpectedly, handle the error
result = server_handle => {
match result {
Ok(Ok(())) => println!("Metrics server finished gracefully."),
Ok(Err(e)) => eprintln!("Metrics server error: {}", e),
Err(join_err) => eprintln!("Metrics server thread panicked: {}", join_err),
}
}
}
println!("All done!");
}Enums§
- Metrics
Error - Errors that can occur while running the metrics server.
Functions§
- start_
http_ server - Starts a lightweight HTTP server to expose Prometheus-like metrics on
"/metrics".