Skip to content

Commit

Permalink
server: graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
pnmadelaine committed Sep 29, 2023
1 parent 69bcd3e commit 8e9ea43
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 3 deletions.
12 changes: 12 additions & 0 deletions typhon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,15 @@ pub fn log_event(event: Event) {
LISTENERS.lock().await.log(event);
});
}

pub async fn shutdown() {
let res = tokio::signal::ctrl_c().await;
eprintln!("Typhon is shutting down...");
let _ = res.map_err(|e| log::error!("{}", e));
tokio::join!(
EVALUATIONS.shutdown(),
JOBS_BUILD.shutdown(),
JOBS_POST.shutdown(),
JOBS_PRE.shutdown(),
);
}
13 changes: 10 additions & 3 deletions typhon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ async fn main() -> std::io::Result<()> {
.expect("failed to run migrations");

// Run actix server
HttpServer::new(|| App::new().configure(typhon::api::config))
let actix = HttpServer::new(|| App::new().configure(typhon::api::config))
.bind(("127.0.0.1", 8000))?
.run()
.await
.run();

// Graceful shutdown
tokio::select! {
_ = actix => panic!(),
_ = typhon::shutdown() => eprintln!("Good bye!"),
}

Ok(())
}
14 changes: 14 additions & 0 deletions typhon/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,18 @@ impl<Id: std::cmp::Eq + std::hash::Hash + std::clone::Clone + Send> Tasks<Id> {
})
.unwrap_or(false)
}

pub async fn keys(&self) -> Vec<Id> {
let tasks = self.tasks.lock().await;
tasks.keys().cloned().collect()
}

pub async fn shutdown(&'static self) {
let mut set = tokio::task::JoinSet::new();
let keys = self.keys().await;
for id in keys {
set.spawn(self.cancel(id));
}
while let Some(_) = set.join_next().await {}
}
}

0 comments on commit 8e9ea43

Please sign in to comment.