Skip to content

Commit

Permalink
feat(jstzd): listen to os signals
Browse files Browse the repository at this point in the history
  • Loading branch information
huancheng-trili committed Nov 26, 2024
1 parent 797bb89 commit 8bca73f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
9 changes: 8 additions & 1 deletion crates/jstzd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
}
Expand Down
30 changes: 30 additions & 0 deletions crates/jstzd/tests/main_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@ fn unknown_command() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

#[test]
fn default_config() -> Result<(), Box<dyn std::error::Error>> {
// 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<dyn std::error::Error>> {
let port = unused_port();
Expand Down Expand Up @@ -75,3 +90,18 @@ fn bad_config_file() -> Result<(), Box<dyn std::error::Error>> {

Ok(())
}

#[test]
fn terminate_with_sigint() -> Result<(), Box<dyn std::error::Error>> {
// 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(())
}

0 comments on commit 8bca73f

Please sign in to comment.