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 30, 2023
1 parent 8f596f0 commit 777be1f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 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(())
}
15 changes: 14 additions & 1 deletion typhon/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct Tasks<Id> {
tasks: Mutex<HashMap<Id, TaskHandle>>,
}

impl<Id: std::cmp::Eq + std::hash::Hash + std::clone::Clone + Send> Tasks<Id> {
impl<Id: std::cmp::Eq + std::hash::Hash + std::clone::Clone + Send + Sync> Tasks<Id> {
pub fn new() -> Self {
Tasks {
tasks: Mutex::new(HashMap::new()),
Expand Down Expand Up @@ -83,4 +83,17 @@ impl<Id: std::cmp::Eq + std::hash::Hash + std::clone::Clone + Send> Tasks<Id> {
.flatten()
.is_some()
}

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

0 comments on commit 777be1f

Please sign in to comment.