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 497269b
Show file tree
Hide file tree
Showing 3 changed files with 41 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(())
}
20 changes: 19 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 @@ -91,4 +91,22 @@ 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 keys = self.keys().await;
let mut set = tokio::task::JoinSet::new();
for id in keys.iter() {
let id = id.clone();
set.spawn(async move { self.wait(&id).await });
}
for id in keys {
self.cancel(id).await;
}
while let Some(_) = set.join_next().await {}
}
}

0 comments on commit 497269b

Please sign in to comment.