Clean up
Some checks failed
Build and Publish Docker Image / test (push) Failing after 7s
Build and Publish Docker Image / build-and-push (push) Has been skipped
Build and Publish Docker Image / security-scan (push) Has been skipped

This commit is contained in:
Andras Schmelczer 2026-06-06 19:41:55 +01:00
commit b414c05400

View file

@ -14,22 +14,18 @@ pub struct HealthHandle {
last_update_success: Arc<Mutex<bool>>,
}
impl Default for HealthServer {
fn default() -> Self {
Self::new().0
}
}
impl HealthServer {
pub fn new() -> (Self, HealthHandle) {
let last_update_success = Arc::new(Mutex::new(true));
let server = Self {
let handle = HealthHandle {
last_update_success: last_update_success.clone(),
};
let handle = HealthHandle {
last_update_success,
};
(server, handle)
(
Self {
last_update_success,
},
handle,
)
}
pub async fn start(self) -> anyhow::Result<()> {
@ -37,64 +33,56 @@ impl HealthServer {
info!("Health server listening on port 8080");
loop {
let (mut socket, _) = listener.accept().await?;
let (socket, _) = match listener.accept().await {
Ok(conn) => conn,
Err(e) => {
warn!("Failed to accept connection: {}", e);
continue;
}
};
let health_status = self.last_update_success.clone();
tokio::spawn(async move {
// Set timeout for the entire request handling (5 seconds)
let handle_request = async {
let mut buffer = [0; 1024];
// Read with timeout to prevent hanging connections
match timeout(Duration::from_secs(5), socket.read(&mut buffer)).await {
Ok(Ok(_)) => {
// Successfully read request (we don't need to parse it for health check)
}
Ok(Err(_)) | Err(_) => {
warn!("Health check request read timeout or error");
return;
}
}
// Safely access health status without panicking
let is_healthy = match health_status.lock() {
Ok(status) => *status,
Err(_) => {
warn!("Health status mutex poisoned, defaulting to unhealthy");
false
}
};
let (status_line, json_body) = if is_healthy {
("HTTP/1.1 200 OK", "{\"status\":\"healthy\"}")
} else {
(
"HTTP/1.1 503 Service Unavailable",
"{\"status\":\"unhealthy\"}",
)
};
let response = format!(
"{}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
status_line,
json_body.len(),
json_body
);
let _ = timeout(
Duration::from_secs(5),
socket.write_all(response.as_bytes()),
)
.await;
};
// Overall timeout for the entire connection handling
let _ = timeout(Duration::from_secs(10), handle_request).await;
let _ = timeout(Duration::from_secs(10), async {
handle_connection(socket, health_status).await;
})
.await;
});
}
}
}
async fn handle_connection(mut socket: tokio::net::TcpStream, health_status: Arc<Mutex<bool>>) {
let mut buffer = [0; 1024];
match timeout(Duration::from_secs(5), socket.read(&mut buffer)).await {
Ok(Ok(0)) | Ok(Err(_)) | Err(_) => return,
Ok(Ok(_)) => {}
}
let is_healthy = health_status.lock().map(|s| *s).unwrap_or(false);
let (status_line, json_body) = if is_healthy {
("HTTP/1.1 200 OK", r#"{"status":"healthy"}"#)
} else {
(
"HTTP/1.1 503 Service Unavailable",
r#"{"status":"unhealthy"}"#,
)
};
let response = format!(
"{status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{json_body}",
json_body.len(),
);
let _ = timeout(
Duration::from_secs(5),
socket.write_all(response.as_bytes()),
)
.await;
}
impl HealthHandle {
pub fn set_health_status(&self, is_healthy: bool) {
if let Ok(mut status) = self.last_update_success.lock() {
@ -103,12 +91,10 @@ impl HealthHandle {
}
pub fn report_update_success(&self) {
info!("Update succeeded - marking health as healthy");
self.set_health_status(true);
}
pub fn report_update_failure(&self) {
info!("Update failed - marking health as unhealthy");
self.set_health_status(false);
}
}