use dragonfly_client_util::shutdown;
use std::net::SocketAddr;
use tokio::sync::mpsc;
use tracing::{info, instrument};
use warp::{Filter, Rejection, Reply};
#[derive(Debug)]
pub struct Health {
addr: SocketAddr,
shutdown: shutdown::Shutdown,
_shutdown_complete: mpsc::UnboundedSender<()>,
}
impl Health {
pub fn new(
addr: SocketAddr,
shutdown: shutdown::Shutdown,
shutdown_complete_tx: mpsc::UnboundedSender<()>,
) -> Self {
Self {
addr,
shutdown,
_shutdown_complete: shutdown_complete_tx,
}
}
pub async fn run(&self) {
let mut shutdown = self.shutdown.clone();
let health_route = warp::path!("healthy")
.and(warp::get())
.and(warp::path::end())
.and_then(Self::health_handler);
info!("health server listening on {}", self.addr);
tokio::select! {
_ = warp::serve(health_route).run(self.addr) => {
info!("health server ended");
}
_ = shutdown.recv() => {
info!("health server shutting down");
}
}
}
#[instrument(skip_all)]
async fn health_handler() -> Result<impl Reply, Rejection> {
Ok(warp::reply())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
#[test]
fn test_health_new() {
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
let shutdown = shutdown::Shutdown::new();
let (shutdown_complete_tx, _shutdown_complete_rx) = mpsc::unbounded_channel();
let health = Health::new(addr, shutdown, shutdown_complete_tx);
assert_eq!(health.addr, addr);
}
#[tokio::test]
async fn test_health_handler() {
let result = Health::health_handler().await;
assert!(result.is_ok());
}
}