use super::state::{Health, HealthReport};
use crate::error::{Context, Error};
use crate::shutdown::CancellationToken;
use bytes::Bytes;
use http_body_util::Full;
use hyper::{
Method, Request, Response, StatusCode, body::Incoming, header, server::conn::http1,
service::service_fn,
};
use hyper_util::{rt::TokioIo, server::graceful::GracefulShutdown};
use std::{
convert::Infallible,
io,
net::{self, SocketAddr},
time::Duration,
};
use tokio::net::TcpListener;
use tracing::{debug, warn};
const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
pub struct HealthServer {
listener: net::TcpListener,
local_addr: SocketAddr,
}
impl HealthServer {
pub fn bind(addr: SocketAddr) -> Result<Self, Error> {
let bind = || -> io::Result<Self> {
let listener = net::TcpListener::bind(addr)?;
listener.set_nonblocking(true)?;
Ok(Self {
local_addr: listener.local_addr()?,
listener,
})
};
bind().with_context(|| format!("binding the health server to {addr}"))
}
pub fn local_addr(&self) -> SocketAddr {
self.local_addr
}
pub(crate) async fn serve(self, health: Health, stop: CancellationToken) -> Result<(), Error> {
let listener =
TcpListener::from_std(self.listener).context("starting the health server")?;
let graceful = GracefulShutdown::new();
loop {
let stream = tokio::select! {
biased;
_ = stop.cancelled() => break,
accepted = listener.accept() => match accepted {
Ok((stream, _)) => stream,
Err(error) => {
warn!(error = %error, "health accept failed");
tokio::time::sleep(ACCEPT_BACKOFF).await;
continue;
}
},
};
let health = health.clone();
let service = service_fn(move |request| {
let response = respond(&request, &health);
async move { Ok::<_, Infallible>(response) }
});
let connection = graceful
.watch(http1::Builder::new().serve_connection(TokioIo::new(stream), service));
tokio::spawn(async move {
if let Err(error) = connection.await {
debug!(error = %error, "health connection closed with an error");
}
});
}
drop(listener);
graceful.shutdown().await;
Ok(())
}
}
fn respond(request: &Request<Incoming>, health: &Health) -> Response<Full<Bytes>> {
let probe: fn(&HealthReport) -> bool = match request.uri().path() {
"/livez" => |report| report.live,
"/readyz" => |report| report.ready,
_ => return status(StatusCode::NOT_FOUND),
};
if request.method() != Method::GET {
let mut response = status(StatusCode::METHOD_NOT_ALLOWED);
response
.headers_mut()
.insert(header::ALLOW, header::HeaderValue::from_static("GET"));
return response;
}
let report = health.report();
let mut response = match serde_json::to_vec(&report) {
Ok(body) => Response::new(Full::from(body)),
Err(_) => return status(StatusCode::INTERNAL_SERVER_ERROR),
};
response.headers_mut().insert(
header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"),
);
if !probe(&report) {
*response.status_mut() = StatusCode::SERVICE_UNAVAILABLE;
}
response
}
fn status(status: StatusCode) -> Response<Full<Bytes>> {
let mut response = Response::new(Full::default());
*response.status_mut() = status;
response
}