diff --git a/crates/jstzd/src/lib.rs b/crates/jstzd/src/lib.rs index ae1f46b3b..62d925d02 100644 --- a/crates/jstzd/src/lib.rs +++ b/crates/jstzd/src/lib.rs @@ -8,6 +8,7 @@ use crate::task::{ }; pub use config::BOOTSTRAP_CONTRACT_NAMES; use std::process::exit; +use tokio::signal::unix::{signal, SignalKind}; pub const EXCHANGER_ADDRESS: &str = "KT1F3MuqvT9Yz57TgCS3EkDcKNZe9HpiavUJ"; pub const JSTZ_ROLLUP_ADDRESS: &str = "sr1PuFMgaRUN12rKQ3J2ae5psNtwCxPNmGNK"; @@ -36,8 +37,14 @@ async fn run(port: u16, config: JstzdConfig) { } wait_for_server(&mut server).await; - server.wait().await; + let mut sigterm = signal(SignalKind::terminate()).unwrap(); + let mut sigint = signal(SignalKind::interrupt()).unwrap(); + tokio::select! { + _ = server.wait() => (), + _ = sigterm.recv() => (), + _ = sigint.recv() => (), + }; println!("Shutting down"); server.stop().await.unwrap(); } diff --git a/crates/jstzd/tests/main_test.rs b/crates/jstzd/tests/main_test.rs index a40cce282..89674a4e3 100644 --- a/crates/jstzd/tests/main_test.rs +++ b/crates/jstzd/tests/main_test.rs @@ -17,6 +17,21 @@ fn unknown_command() -> Result<(), Box> { Ok(()) } +#[test] +fn default_config() -> Result<(), Box> { + // Since the server's port number is unknown when jstzd runs on default config, + // here it's assumed that if the child process is still alive after 10 seconds, + // it means that jstzd successfully launched + let mut child = Command::cargo_bin("jstzd")?.arg("run").spawn()?; + std::thread::sleep(std::time::Duration::from_secs(10)); + assert!(child.try_wait()?.is_none()); + Command::new("kill") + .args(["-s", "TERM", &child.id().to_string()]) + .spawn()?; + assert!(child.wait()?.success()); + Ok(()) +} + #[test] fn valid_config_file() -> Result<(), Box> { let port = unused_port(); @@ -75,3 +90,18 @@ fn bad_config_file() -> Result<(), Box> { Ok(()) } + +#[test] +fn terminate_with_sigint() -> Result<(), Box> { + // Since the server's port number is unknown when jstzd runs on default config, + // here it's assumed that if the child process is still alive after 10 seconds, + // it means that jstzd successfully launched + let mut child = Command::cargo_bin("jstzd")?.arg("run").spawn()?; + std::thread::sleep(std::time::Duration::from_secs(10)); + assert!(child.try_wait()?.is_none()); + Command::new("kill") + .args(["-s", "INT", &child.id().to_string()]) + .spawn()?; + assert!(child.wait()?.success()); + Ok(()) +}