better shutdown, still not perfect

This commit is contained in:
Joe Ardent 2025-07-06 21:43:24 -07:00
parent 342b634388
commit c02e4bc879
6 changed files with 32 additions and 23 deletions

2
Cargo.lock generated
View file

@ -2158,9 +2158,7 @@ dependencies = [
"io-uring",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"slab",
"socket2",
"tokio-macros",

View file

@ -19,5 +19,5 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha256 = "1.6"
thiserror = "2"
tokio = { version = "1", features = ["full", "macros", "rt-multi-thread"] }
tokio = { version = "1", default-features = false, features = ["time", "macros", "rt-multi-thread"] }
tower-http = { version = "0.6", features = ["limit"] }

View file

@ -1,6 +1,7 @@
use std::{
net::{SocketAddr, SocketAddrV4},
sync::Arc,
time::Duration,
};
use axum::{
@ -27,8 +28,20 @@ impl JoecalState {
println!("Socket local addr: {:?}", self.socket.local_addr()?);
println!("Listening on multicast addr: {}", config.multicast_addr);
let mut timeout = tokio::time::interval(Duration::from_secs(5));
timeout.tick().await;
loop {
match self.socket.recv_from(&mut buf).await {
tokio::select! {
_ = timeout.tick() => {
if let Ok(state) = self.running_state.try_lock()
&& *state == RunningState::Stopping
{
break;
}
},
r = self.socket.recv_from(&mut buf) => {
match r {
Ok((size, src)) => {
let received_msg = String::from_utf8_lossy(&buf[..size]);
self.process_device(&received_msg, src, config).await;
@ -38,10 +51,7 @@ impl JoecalState {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
}
}
if let Ok(state) = self.running_state.try_lock()
&& *state == RunningState::Stopping
{
break;
}
}
}
Ok(())

View file

@ -8,7 +8,6 @@ use std::{
collections::HashMap,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
time::Duration,
};
use models::Device;
@ -85,15 +84,16 @@ impl JoecalState {
let announcement_handle = {
tokio::spawn(async move {
loop {
if let Err(e) = state.announce(None, &config).await {
eprintln!("Announcement error: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
if let Ok(lock) = state.running_state.try_lock()
&& *lock == RunningState::Stopping
{
break;
}
if let Err(e) = state.announce(None, &config).await {
eprintln!("Announcement error: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
})
};

View file

@ -50,6 +50,7 @@ async fn main() -> error::Result<()> {
let mut terminal = ratatui::init();
let result = app.run(&mut terminal).await;
ratatui::restore();
let _ = tokio::join!(h1, h2, h3);
Ok(result?)

View file

@ -48,8 +48,8 @@ impl FileMetadata {
let sha256 = Some(sha256::try_digest(path)?);
let metadata = Some(FileMetadataExt {
modified: metadata.modified().ok().map(|t| format_datetime(t)),
accessed: metadata.accessed().ok().map(|t| format_datetime(t)),
modified: metadata.modified().ok().map(format_datetime),
accessed: metadata.accessed().ok().map(format_datetime),
});
Ok(FileMetadata {