Skip to content

Commit

Permalink
Add comments to http_metrics crate
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Sep 22, 2020
1 parent dc2518d commit 4472e5a
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions beacon_node/http_metrics/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
//! This crate provides a HTTP server that is solely dedicated to serving the `/metrics` endpoint.
//!
//! For other endpoints, see the `http_api` crate.
#[macro_use]
extern crate lazy_static;

Expand Down Expand Up @@ -31,6 +35,9 @@ impl From<String> for Error {
}
}

/// A wrapper around all the items required to spawn the HTTP server.
///
/// The server will gracefully handle the case where any fields are `None`.
pub struct Context<T: BeaconChainTypes> {
pub config: Config,
pub chain: Option<Arc<BeaconChain<T>>>,
Expand All @@ -39,6 +46,7 @@ pub struct Context<T: BeaconChainTypes> {
pub log: Logger,
}

/// Configuration for the HTTP server.
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct Config {
pub enabled: bool,
Expand All @@ -58,6 +66,21 @@ impl Default for Config {
}
}

/// Creates a server that will serve requests using information from `ctx`.
///
/// The server will shut down gracefully when the `shutdown` future resolves.
///
/// ## Returns
///
/// This function will bind the server to the provided address and then return a tuple of:
///
/// - `SocketAddr`: the address that the HTTP server will listen on.
/// - `Future`: the actual server future that will need to be awaited.
///
/// ## Errors
///
/// Returns an error if the server is unable to bind or there is another error during
/// configuration.
pub fn serve<T: BeaconChainTypes>(
ctx: Arc<Context<T>>,
shutdown: impl Future<Output = ()> + Send + Sync + 'static,
Expand All @@ -66,6 +89,7 @@ pub fn serve<T: BeaconChainTypes>(
let log = ctx.log.clone();
let allow_origin = config.allow_origin.clone();

// Sanity check.
if !config.enabled {
crit!(log, "Cannot start disabled metrics HTTP server");
return Err(Error::Other(
Expand All @@ -89,7 +113,9 @@ pub fn serve<T: BeaconChainTypes>(
}),
)
})
// Add a `Server` header.
.map(|reply| warp::reply::with_header(reply, "Server", &version_with_platform()))
// Maybe add some CORS headers.
.map(move |reply| warp_utils::reply::maybe_cors(reply, allow_origin.as_ref()));

let (listening_socket, server) = warp::serve(routes).try_bind_with_graceful_shutdown(
Expand Down

0 comments on commit 4472e5a

Please sign in to comment.