Skip to content

Commit

Permalink
Move to error struct
Browse files Browse the repository at this point in the history
  • Loading branch information
eloylp committed Apr 12, 2024
1 parent b683961 commit 76d6d59
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions ampd/src/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use error_stack::{Result, ResultExt};
use std::net::SocketAddrV4;
use std::{fmt::Display, net::SocketAddrV4};
use thiserror::Error;
use tracing::info;

Expand All @@ -15,17 +15,28 @@ pub struct Server {
}

#[derive(Error, Debug)]
pub enum HealthCheckError {
#[error("Health check server error: {0}")]
Error(String),
pub struct HealthCheckError {
msg: String,
}

impl HealthCheckError {
pub fn new(msg: String) -> Self {
Self { msg }
}
}

impl Display for HealthCheckError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.msg)
}
}

impl Server {
pub async fn new(bind_addr: SocketAddrV4) -> Result<Self, HealthCheckError> {
Ok(Self {
listener: tokio::net::TcpListener::bind(bind_addr)
.await
.change_context(HealthCheckError::Error(format!(
.change_context(HealthCheckError::new(format!(
"Failed binding to addr: {}",
bind_addr
)))?,
Expand All @@ -37,23 +48,21 @@ impl Server {
Ok(self
.listener
.local_addr()
.map_err(|e| HealthCheckError::Error(e.to_string()))?)
.map_err(|e| HealthCheckError::new(e.to_string()))?)
}
pub async fn run(self, cancel: CancellationToken) -> Result<(), HealthCheckError> {
let app = Router::new().route("/status", get(status));
let bind_address = self
.listener
.local_addr()
.change_context(HealthCheckError::Error(
.change_context(HealthCheckError::new(
"Failed getting local address".to_string(),
))?;
info!("Starting health check server at: {}", bind_address);
axum::serve(self.listener, app)
.with_graceful_shutdown(async move { cancel.cancelled().await })
.await
.change_context(HealthCheckError::Error(
"Failed executing server".to_string(),
))
.change_context(HealthCheckError::new("Failed executing server".to_string()))
}
}

Expand Down

0 comments on commit 76d6d59

Please sign in to comment.