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 29, 2024
1 parent 27a422d commit 76a4947
Show file tree
Hide file tree
Showing 2 changed files with 46 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 @@ -5,6 +5,7 @@ pub mod task;
use crate::task::jstzd::{JstzdConfig, JstzdServer};
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 @@ -32,8 +33,14 @@ async fn run(port: u16, config: JstzdConfig) {
exit(1);
}

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();
}
38 changes: 38 additions & 0 deletions crates/jstzd/tests/main_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,25 @@ fn unknown_command() {
.stderr(predicate::str::contains("unrecognized subcommand \'test\'"));
}

#[test]
fn default_config() {
// 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")
.unwrap()
.arg("run")
.spawn()
.unwrap();
thread::sleep(Duration::from_secs(10));
assert!(child.try_wait().unwrap().is_none());
Command::new("kill")
.args(["-s", "TERM", &child.id().to_string()])
.spawn()
.unwrap();
assert!(child.wait().is_ok());
}

#[test]
fn valid_config_file() {
let port = unused_port();
Expand Down Expand Up @@ -74,3 +93,22 @@ fn bad_config_file() {
"should have at least one bootstrap account with at least 6000 tez",
));
}

#[test]
fn terminate_with_sigint() {
// 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")
.unwrap()
.arg("run")
.spawn()
.unwrap();
thread::sleep(Duration::from_secs(10));
assert!(child.try_wait().unwrap().is_none());
Command::new("kill")
.args(["-s", "INT", &child.id().to_string()])
.spawn()
.unwrap();
assert!(child.wait().is_ok());
}

0 comments on commit 76a4947

Please sign in to comment.